Skip to content

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

feat: support generate pg column migration for ast-only (#17448)

rebeliceeca238b68f5b
diff --git a/backend/plugin/schema/pg/column_migration_integration_test.go b/backend/plugin/schema/pg/column_migration_integration_test.go
new file mode 100644
index 0000000000..0915cadac9
--- /dev/null
+++ b/backend/plugin/schema/pg/column_migration_integration_test.go
@@ -0,0 +1,463 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+)
+
+func TestColumnSDLDiffAndMigrationIntegration(t *testing.T) {
+ tests := []struct {
+ name string
+ previousSDL string
+ currentSDL string
+ expectedMigration string
+ }{
+ {
+ name: "Add new column",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(320) UNIQUE
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" ADD COLUMN email VARCHAR(320) UNIQUE;
+
+`,
+ },
+ {
+ name: "Drop column",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ phone VARCHAR(20)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" DROP COLUMN IF EXISTS "phone";
+
+`,
+ },
+ {
+ name: "Modify column (ALTER TYPE)",
+ previousSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(15,3) NOT NULL DEFAULT 0.00
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."products" ALTER COLUMN "price" TYPE DECIMAL(15,3);
+ALTER TABLE "public"."products" ALTER COLUMN "price" SET DEFAULT 0.00;
+
+`,
+ },
+ {
+ name: "Modify column nullable",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320) NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" ALTER COLUMN "email" SET NOT NULL;
+
+`,
+ },
+ {
+ name: "Drop column nullable constraint",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320)
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" ALTER COLUMN "email" DROP NOT NULL;
+
+`,
+ },
+ {
+ name: "Add default value to existing column",
+ previousSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL DEFAULT 9.99
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."products" ALTER COLUMN "price" SET DEFAULT 9.99;
+
+`,
+ },
+ {
+ name: "Drop default value from column",
+ previousSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL DEFAULT 9.99
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."products" ALTER COLUMN "price" DROP DEFAULT;
+
+`,
+ },
+ {
+ name: "Change column type only",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" ALTER COLUMN "name" TYPE VARCHAR(255);
+
+`,
+ },
+ {
+ name: "Multiple column changes in same table",
+ previousSDL: `
+ CREATE TABLE employees (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100),
+ email VARCHAR(255) NOT NULL,
+ salary DECIMAL(8,2)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE employees (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(200) NOT NULL,
+ email VARCHAR(320) NOT NULL,
+ salary DECIMAL(10,2) DEFAULT 50000.00
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."employees" ALTER COLUMN "name" TYPE VARCHAR(200);
+ALTER TABLE "public"."employees" ALTER COLUMN "name" SET NOT NULL;
+ALTER TABLE "public"."employees" ALTER COLUMN "email" TYPE VARCHAR(320);
+ALTER TABLE "public"."employees" ALTER COLUMN "salary" TYPE DECIMAL(10,2);
+ALTER TABLE "public"."employees" ALTER COLUMN "salary" SET DEFAULT 50000.00;
+
+`,
+ },
+ {
+ name: "Add column with complex constraints",
+ previousSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ status VARCHAR(20) NOT NULL DEFAULT 'pending'
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."orders" ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'pending';
+
+`,
+ },
+ {
+ name: "Change column from nullable to not null with default",
+ previousSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ category VARCHAR(50)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ category VARCHAR(50) NOT NULL DEFAULT 'general'
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."products" ALTER COLUMN "category" SET NOT NULL;
+ALTER TABLE "public"."products" ALTER COLUMN "category" SET DEFAULT 'general';
+
+`,
+ },
+ {
+ name: "Complex type change with precision",
+ previousSDL: `
+ CREATE TABLE measurements (
+ id SERIAL PRIMARY KEY,
+ value DECIMAL(5,2)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE measurements (
+ id SERIAL PRIMARY KEY,
+ value DECIMAL(10,4) NOT NULL DEFAULT 0.0000
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."measurements" ALTER COLUMN "value" TYPE DECIMAL(10,4);
+ALTER TABLE "public"."measurements" ALTER COLUMN "value" SET NOT NULL;
+ALTER TABLE "public"."measurements" ALTER COLUMN "value" SET DEFAULT 0.0000;
+
+`,
+ },
+ {
+ name: "Add multiple columns",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ email VARCHAR(320) UNIQUE,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" ADD COLUMN email VARCHAR(320) UNIQUE;
+ALTER TABLE "public"."users" ADD COLUMN created_at TIMESTAMP DEFAULT NOW();
+
+`,
+ },
+ {
+ name: "Drop multiple columns",
+ previousSDL: `
+ CREATE TABLE temp_data (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ temp_field1 VARCHAR(100),
+ temp_field2 INTEGER,
+ description TEXT
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE temp_data (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ description TEXT
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."temp_data" DROP COLUMN IF EXISTS "temp_field1";
+ALTER TABLE "public"."temp_data" DROP COLUMN IF EXISTS "temp_field2";
+
+`,
+ },
+ {
+ name: "Mixed operations: add, drop, modify",
+ previousSDL: `
+ CREATE TABLE inventory (
+ id SERIAL PRIMARY KEY,
+ product_name VARCHAR(100) NOT NULL,
+ old_field VARCHAR(50),
+ quantity INTEGER DEFAULT 0
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE inventory (
+ id SERIAL PRIMARY KEY,
+ product_name VARCHAR(200) NOT NULL,
+ quantity INTEGER DEFAULT 1,
+ location VARCHAR(100) NOT NULL DEFAULT 'warehouse'
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."inventory" DROP COLUMN IF EXISTS "old_field";
+
+ALTER TABLE "public"."inventory" ADD COLUMN location VARCHAR(100) NOT NULL DEFAULT 'warehouse';
+ALTER TABLE "public"."inventory" ALTER COLUMN "product_name" TYPE VARCHAR(200);
+ALTER TABLE "public"."inventory" ALTER COLUMN "quantity" SET DEFAULT 1;
+
+`,
+ },
+ {
+ name: "Integer type variations",
+ previousSDL: `
+ CREATE TABLE counters (
+ id SERIAL PRIMARY KEY,
+ small_count SMALLINT,
+ big_count BIGINT
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE counters (
+ id SERIAL PRIMARY KEY,
+ small_count INTEGER NOT NULL DEFAULT 0,
+ big_count BIGINT NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."counters" ALTER COLUMN "small_count" TYPE INTEGER;
+ALTER TABLE "public"."counters" ALTER COLUMN "small_count" SET NOT NULL;
+ALTER TABLE "public"."counters" ALTER COLUMN "small_count" SET DEFAULT 0;
+ALTER TABLE "public"."counters" ALTER COLUMN "big_count" SET NOT NULL;
+
+`,
+ },
+ {
+ name: "Text and character types",
+ previousSDL: `
+ CREATE TABLE documents (
+ id SERIAL PRIMARY KEY,
+ title CHAR(50),
+ content TEXT
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE documents (
+ id SERIAL PRIMARY KEY,
+ title VARCHAR(100) NOT NULL,
+ content TEXT DEFAULT ''
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."documents" ALTER COLUMN "title" TYPE VARCHAR(100);
+ALTER TABLE "public"."documents" ALTER COLUMN "title" SET NOT NULL;
+ALTER TABLE "public"."documents" ALTER COLUMN "content" SET DEFAULT '';
+
+`,
+ },
+ {
+ name: "Boolean column with default",
+ previousSDL: `
+ CREATE TABLE features (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE features (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ enabled BOOLEAN NOT NULL DEFAULT false
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."features" ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT false;
+
+`,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Step 1: Get SDL diff using AST-only mode (no metadata extraction)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Step 2: Verify that diff contains column changes with AST nodes
+ if len(diff.TableChanges) > 0 {
+ for _, tableDiff := range diff.TableChanges {
+ for _, colDiff := range tableDiff.ColumnChanges {
+ switch colDiff.Action {
+ case schema.MetadataDiffActionCreate:
+ assert.NotNil(t, colDiff.NewASTNode,
+ "Create action should have NewASTNode")
+ assert.Nil(t, colDiff.OldASTNode,
+ "Create action should not have OldASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, colDiff.NewColumn,
+ "AST-only mode should not have metadata")
+ case schema.MetadataDiffActionDrop:
+ assert.NotNil(t, colDiff.OldASTNode,
+ "Drop action should have OldASTNode")
+ assert.Nil(t, colDiff.NewASTNode,
+ "Drop action should not have NewASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, colDiff.OldColumn,
+ "AST-only mode should not have metadata")
+ case schema.MetadataDiffActionAlter:
+ assert.NotNil(t, colDiff.OldASTNode,
+ "Alter action should have OldASTNode")
+ assert.NotNil(t, colDiff.NewASTNode,
+ "Alter action should have NewASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, colDiff.OldColumn,
+ "AST-only mode should not have metadata")
+ assert.Nil(t, colDiff.NewColumn,
+ "AST-only mode should not have metadata")
+ default:
+ // Other actions
+ t.Logf("Encountered column action: %v", colDiff.Action)
+ }
+ }
+ }
+ }
+
+ // Step 3: Generate migration SQL using AST nodes
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+
+ // Step 4: Verify the generated migration matches expectations
+ assert.Equal(t, tt.expectedMigration, migrationSQL,
+ "Generated migration SQL should match expected output")
+
+ // Step 5: Verify the migration contains expected keywords for columns
+ if tt.expectedMigration != "" {
+ if containsColumnString(tt.expectedMigration, "ADD COLUMN") {
+ assert.Contains(t, migrationSQL, "ADD COLUMN",
+ "Migration should contain ADD COLUMN statement")
+ }
+ if containsColumnString(tt.expectedMigration, "DROP COLUMN") {
+ assert.Contains(t, migrationSQL, "DROP COLUMN",
+ "Migration should contain DROP COLUMN statement")
+ }
+ if containsColumnString(tt.expectedMigration, "ALTER COLUMN") {
+ assert.Contains(t, migrationSQL, "ALTER COLUMN",
+ "Migration should contain ALTER COLUMN statement")
+ }
+ }
+ })
+ }
+}
+
+// Helper function to check if a string contains a substring
+func containsColumnString(s, substr string) bool {
+ return strings.Contains(s, substr)
+}
diff --git a/backend/plugin/schema/pg/column_sdl_diff_test.go b/backend/plugin/schema/pg/column_sdl_diff_test.go
index 9235be0c19..f45a6eb621 100644
--- a/backend/plugin/schema/pg/column_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/column_sdl_diff_test.go
@@ -65,14 +65,16 @@ func TestColumnSDLDiff(t *testing.T) {
columnDiff := columnDiffs[0]
assert.Equal(t, schema.MetadataDiffActionCreate, columnDiff.Action, "Should be CREATE action")
- assert.Nil(t, columnDiff.OldColumn, "CREATE should have nil OldColumn")
- assert.NotNil(t, columnDiff.NewColumn, "CREATE should have NewColumn")
- assert.Equal(t, "email", columnDiff.NewColumn.Name, "Column name should match")
- assert.Contains(t, columnDiff.NewColumn.Type, "VARCHAR", "Should contain VARCHAR type")
+ assert.Nil(t, columnDiff.OldColumn, "CREATE should have nil OldColumn in AST-only mode")
+ assert.Nil(t, columnDiff.NewColumn, "CREATE should have nil NewColumn in AST-only mode")
// Verify AST nodes
assert.Nil(t, columnDiff.OldASTNode, "CREATE should have nil OldASTNode")
assert.NotNil(t, columnDiff.NewASTNode, "CREATE should have NewASTNode")
+
+ // Extract column name from AST for verification
+ columnName := extractColumnNameFromAST(columnDiff.NewASTNode)
+ assert.Equal(t, "email", columnName, "Column name should match")
},
},
{
@@ -96,13 +98,16 @@ func TestColumnSDLDiff(t *testing.T) {
columnDiff := columnDiffs[0]
assert.Equal(t, schema.MetadataDiffActionDrop, columnDiff.Action, "Should be DROP action")
- assert.NotNil(t, columnDiff.OldColumn, "DROP should have OldColumn")
+ assert.Nil(t, columnDiff.OldColumn, "DROP should have nil OldColumn in AST-only mode")
assert.Nil(t, columnDiff.NewColumn, "DROP should have nil NewColumn")
- assert.Equal(t, "email", columnDiff.OldColumn.Name, "Column name should match")
// Verify AST nodes
assert.NotNil(t, columnDiff.OldASTNode, "DROP should have OldASTNode")
assert.Nil(t, columnDiff.NewASTNode, "DROP should have nil NewASTNode")
+
+ // Extract column name from AST for verification
+ columnName := extractColumnNameFromAST(columnDiff.OldASTNode)
+ assert.Equal(t, "email", columnName, "Column name should match")
},
},
{
@@ -125,17 +130,19 @@ func TestColumnSDLDiff(t *testing.T) {
columnDiff := columnDiffs[0]
assert.Equal(t, schema.MetadataDiffActionAlter, columnDiff.Action, "Should be ALTER action")
- assert.NotNil(t, columnDiff.OldColumn, "ALTER should have OldColumn")
- assert.NotNil(t, columnDiff.NewColumn, "ALTER should have NewColumn")
- assert.Equal(t, "name", columnDiff.OldColumn.Name, "Old column name should match")
- assert.Equal(t, "name", columnDiff.NewColumn.Name, "New column name should match")
- assert.Contains(t, columnDiff.OldColumn.Type, "VARCHAR(255)", "Old type should contain VARCHAR(255)")
- assert.Contains(t, columnDiff.NewColumn.Type, "TEXT", "New type should contain TEXT")
+ assert.Nil(t, columnDiff.OldColumn, "ALTER should have nil OldColumn in AST-only mode")
+ assert.Nil(t, columnDiff.NewColumn, "ALTER should have nil NewColumn in AST-only mode")
// Verify AST nodes
assert.NotNil(t, columnDiff.OldASTNode, "ALTER should have OldASTNode")
assert.NotNil(t, columnDiff.NewASTNode, "ALTER should have NewASTNode")
+ // Extract column names from AST for verification
+ oldColumnName := extractColumnNameFromAST(columnDiff.OldASTNode)
+ newColumnName := extractColumnNameFromAST(columnDiff.NewASTNode)
+ assert.Equal(t, "name", oldColumnName, "Old column name should match")
+ assert.Equal(t, "name", newColumnName, "New column name should match")
+
// Verify AST text extraction
oldText := getColumnText(columnDiff.OldASTNode)
newText := getColumnText(columnDiff.NewASTNode)
@@ -178,22 +185,25 @@ func TestColumnSDLDiff(t *testing.T) {
switch columnDiff.Action {
case schema.MetadataDiffActionCreate:
createCount++
- createColumns = append(createColumns, columnDiff.NewColumn.Name)
- assert.Nil(t, columnDiff.OldColumn, "CREATE should have nil OldColumn")
- assert.NotNil(t, columnDiff.NewColumn, "CREATE should have NewColumn")
+ columnName := extractColumnNameFromAST(columnDiff.NewASTNode)
+ createColumns = append(createColumns, columnName)
+ assert.Nil(t, columnDiff.OldColumn, "CREATE should have nil OldColumn in AST-only mode")
+ assert.Nil(t, columnDiff.NewColumn, "CREATE should have nil NewColumn in AST-only mode")
assert.Nil(t, columnDiff.OldASTNode, "CREATE should have nil OldASTNode")
assert.NotNil(t, columnDiff.NewASTNode, "CREATE should have NewASTNode")
case schema.MetadataDiffActionAlter:
alterCount++
- alterColumns = append(alterColumns, columnDiff.NewColumn.Name)
- assert.NotNil(t, columnDiff.OldColumn, "ALTER should have OldColumn")
- assert.NotNil(t, columnDiff.NewColumn, "ALTER should have NewColumn")
+ columnName := extractColumnNameFromAST(columnDiff.NewASTNode)
+ alterColumns = append(alterColumns, columnName)
+ assert.Nil(t, columnDiff.OldColumn, "ALTER should have nil OldColumn in AST-only mode")
+ assert.Nil(t, columnDiff.NewColumn, "ALTER should have nil NewColumn in AST-only mode")
assert.NotNil(t, columnDiff.OldASTNode, "ALTER should have OldASTNode")
assert.NotNil(t, columnDiff.NewASTNode, "ALTER should have NewASTNode")
case schema.MetadataDiffActionDrop:
dropCount++
- dropColumns = append(dropColumns, columnDiff.OldColumn.Name)
- assert.NotNil(t, columnDiff.OldColumn, "DROP should have OldColumn")
+ columnName := extractColumnNameFromAST(columnDiff.OldASTNode)
+ dropColumns = append(dropColumns, columnName)
+ assert.Nil(t, columnDiff.OldColumn, "DROP should have nil OldColumn in AST-only mode")
assert.Nil(t, columnDiff.NewColumn, "DROP should have nil NewColumn")
assert.NotNil(t, columnDiff.OldASTNode, "DROP should have OldASTNode")
assert.Nil(t, columnDiff.NewASTNode, "DROP should have nil NewASTNode")
@@ -231,8 +241,18 @@ func TestColumnSDLDiff(t *testing.T) {
columnDiff := columnDiffs[0]
assert.Equal(t, schema.MetadataDiffActionAlter, columnDiff.Action, "Should be ALTER action")
- assert.False(t, columnDiff.OldColumn.Nullable, "Old column should not be nullable (has NOT NULL)")
- assert.True(t, columnDiff.NewColumn.Nullable, "New column should be nullable (no NOT NULL)")
+ assert.Nil(t, columnDiff.OldColumn, "Should have nil OldColumn in AST-only mode")
+ assert.Nil(t, columnDiff.NewColumn, "Should have nil NewColumn in AST-only mode")
+
+ // Verify AST nodes are available
+ assert.NotNil(t, columnDiff.OldASTNode, "Should have OldASTNode")
+ assert.NotNil(t, columnDiff.NewASTNode, "Should have NewASTNode")
+
+ // Check constraint differences via AST text
+ oldText := getColumnText(columnDiff.OldASTNode)
+ newText := getColumnText(columnDiff.NewASTNode)
+ assert.Contains(t, oldText, "NOT NULL", "Old AST should contain NOT NULL")
+ assert.NotContains(t, newText, "NOT NULL", "New AST should not contain NOT NULL")
},
},
{
@@ -255,8 +275,18 @@ func TestColumnSDLDiff(t *testing.T) {
columnDiff := columnDiffs[0]
assert.Equal(t, schema.MetadataDiffActionAlter, columnDiff.Action, "Should be ALTER action")
- assert.Equal(t, "'active'", columnDiff.OldColumn.Default, "Old default should match")
- assert.Equal(t, "'inactive'", columnDiff.NewColumn.Default, "New default should match")
+ assert.Nil(t, columnDiff.OldColumn, "Should have nil OldColumn in AST-only mode")
+ assert.Nil(t, columnDiff.NewColumn, "Should have nil NewColumn in AST-only mode")
+
+ // Verify AST nodes are available
+ assert.NotNil(t, columnDiff.OldASTNode, "Should have OldASTNode")
+ assert.NotNil(t, columnDiff.NewASTNode, "Should have NewASTNode")
+
+ // Check default value differences via AST text
+ oldText := getColumnText(columnDiff.OldASTNode)
+ newText := getColumnText(columnDiff.NewASTNode)
+ assert.Contains(t, oldText, "'active'", "Old AST should contain 'active'")
+ assert.Contains(t, newText, "'inactive'", "New AST should contain 'inactive'")
},
},
{
@@ -277,8 +307,18 @@ func TestColumnSDLDiff(t *testing.T) {
columnDiff := columnDiffs[0]
assert.Equal(t, schema.MetadataDiffActionAlter, columnDiff.Action, "Should be ALTER action")
- assert.Equal(t, `"C"`, columnDiff.OldColumn.Collation, "Old collation should match")
- assert.Equal(t, `"en_US"`, columnDiff.NewColumn.Collation, "New collation should match")
+ assert.Nil(t, columnDiff.OldColumn, "Should have nil OldColumn in AST-only mode")
+ assert.Nil(t, columnDiff.NewColumn, "Should have nil NewColumn in AST-only mode")
+
+ // Verify AST nodes are available
+ assert.NotNil(t, columnDiff.OldASTNode, "Should have OldASTNode")
+ assert.NotNil(t, columnDiff.NewASTNode, "Should have NewASTNode")
+
+ // Check collation differences via AST text
+ oldText := getColumnText(columnDiff.OldASTNode)
+ newText := getColumnText(columnDiff.NewASTNode)
+ assert.Contains(t, oldText, `"C"`, "Old AST should contain 'C' collation")
+ assert.Contains(t, newText, `"en_US"`, "New AST should contain 'en_US' collation")
},
},
{
@@ -301,7 +341,8 @@ func TestColumnSDLDiff(t *testing.T) {
columnDiff := columnDiffs[0]
assert.Equal(t, schema.MetadataDiffActionAlter, columnDiff.Action, "Should be ALTER action")
- assert.Equal(t, "id", columnDiff.NewColumn.Name, "Column name should match")
+ columnName := extractColumnNameFromAST(columnDiff.NewASTNode)
+ assert.Equal(t, "id", columnName, "Column name should match")
// Verify that text comparison detects the difference
oldText := getColumnText(columnDiff.OldASTNode)
@@ -414,11 +455,29 @@ func TestColumnSDLDiff(t *testing.T) {
for _, columnChange := range tableDiff.ColumnChanges {
switch columnChange.Action {
case schema.MetadataDiffActionCreate:
- createColumns = append(createColumns, columnChange.NewColumn.Name)
+ if columnChange.NewColumn != nil {
+ createColumns = append(createColumns, columnChange.NewColumn.Name)
+ } else if columnChange.NewASTNode != nil {
+ // AST-only mode: extract column name from AST
+ columnName := extractColumnNameFromAST(columnChange.NewASTNode)
+ createColumns = append(createColumns, columnName)
+ }
case schema.MetadataDiffActionAlter:
- alterColumns = append(alterColumns, columnChange.NewColumn.Name)
+ if columnChange.NewColumn != nil {
+ alterColumns = append(alterColumns, columnChange.NewColumn.Name)
+ } else if columnChange.NewASTNode != nil {
+ // AST-only mode: extract column name from AST
+ columnName := extractColumnNameFromAST(columnChange.NewASTNode)
+ alterColumns = append(alterColumns, columnName)
+ }
case schema.MetadataDiffActionDrop:
- dropColumns = append(dropColumns, columnChange.OldColumn.Name)
+ if columnChange.OldColumn != nil {
+ dropColumns = append(dropColumns, columnChange.OldColumn.Name)
+ } else if columnChange.OldASTNode != nil {
+ // AST-only mode: extract column name from AST
+ columnName := extractColumnNameFromAST(columnChange.OldASTNode)
+ dropColumns = append(dropColumns, columnName)
+ }
default:
t.Fatalf("Unexpected column change action: %v", columnChange.Action)
}
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.go
index 6bb33c9e01..badc235c44 100644
--- a/backend/plugin/schema/pg/generate_migration.go
+++ b/backend/plugin/schema/pg/generate_migration.go
@@ -280,7 +280,13 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
// Drop columns
for _, colDiff := range tableDiff.ColumnChanges {
if colDiff.Action == schema.MetadataDiffActionDrop {
- writeDropColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldColumn.Name)
+ if colDiff.OldColumn != nil {
+ // Metadata mode - use column metadata
+ writeDropColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldColumn.Name)
+ } else if colDiff.OldASTNode != nil {
+ // AST-only mode - use AST functions
+ _ = writeDropColumnFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldASTNode)
+ }
}
}
}
@@ -349,7 +355,13 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
// Drop columns
for _, colDiff := range tableDiff.ColumnChanges {
if colDiff.Action == schema.MetadataDiffActionDrop {
- writeDropColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldColumn.Name)
+ if colDiff.OldColumn != nil {
+ // Metadata mode - use column metadata
+ writeDropColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldColumn.Name)
+ } else if colDiff.OldASTNode != nil {
+ // AST-only mode - use AST functions
+ _ = writeDropColumnFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldASTNode)
+ }
}
}
}
@@ -781,11 +793,15 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error
return errors.Errorf("table CREATE action requires either NewTable metadata or NewASTNode for table %s.%s", tableDiff.SchemaName, tableDiff.TableName)
}
case schema.MetadataDiffActionAlter:
- // Handle column additions for ALTER operations
- for _, colDiff := range tableDiff.ColumnChanges {
- if colDiff.Action == schema.MetadataDiffActionCreate {
- writeAddColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)
- }
+ // Handle ALTER table operations with generateAlterTableWithOptions
+ // Skip foreign keys in the first pass to avoid dependency issues
+ alterTableSQL, err := generateAlterTableWithOptions(tableDiff, true)
+ if err != nil {
+ return err
+ }
+ _, _ = buf.WriteString(alterTableSQL)
+ if alterTableSQL != "" {
+ _, _ = buf.WriteString("\n")
}
default:
// No action needed for other operations
@@ -863,6 +879,32 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error
}
}
+ // Add foreign keys for ALTER table operations after all tables are created
+ for _, tableDiff := range tableMap {
+ if tableDiff.Action == schema.MetadataDiffActionAlter {
+ // Only add foreign keys in this second pass
+ fkSQL, err := generateAlterTableForeignKeys(tableDiff)
+ if err != nil {
+ return err
+ }
+ _, _ = buf.WriteString(fkSQL)
+ if fkSQL != "" {
+ _, _ = buf.WriteString("\n")
+ }
+ }
+ }
+
+ // Add triggers for ALTER table operations after foreign keys
+ for _, tableDiff := range tableMap {
+ if tableDiff.Action == schema.MetadataDiffActionAlter {
+ triggerSQL := generateAlterTableTriggers(tableDiff)
+ _, _ = buf.WriteString(triggerSQL)
+ if triggerSQL != "" {
+ _, _ = buf.WriteString("\n")
+ }
+ }
+ }
+
// Create triggers after foreign keys (only for CREATE table operations)
for _, tableDiff := range tableMap {
if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {
@@ -882,19 +924,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error
}
}
- // Handle ALTER table operations
+ // ALTER table operations are now handled earlier in the topological order
for _, tableDiff := range diff.TableChanges {
if tableDiff.Action == schema.MetadataDiffActionAlter {
- // Skip column additions as they were handled earlier
- alterTableSQL, err := generateAlterTableWithOptions(tableDiff, false)
- if err != nil {
- return err
- }
- _, _ = buf.WriteString(alterTableSQL)
- if alterTableSQL != "" {
- _, _ = buf.WriteString("\n")
- }
-
// Handle table comment changes
if err := generateTableCommentChanges(buf, tableDiff); err != nil {
return err
@@ -990,7 +1022,16 @@ func generateAlterTableWithOptions(tableDiff *schema.TableDiff, includeColumnAdd
if includeColumnAdditions {
for _, colDiff := range tableDiff.ColumnChanges {
if colDiff.Action == schema.MetadataDiffActionCreate {
- writeAddColumn(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)
+ // Support both metadata mode and AST-only mode
+ if colDiff.NewColumn != nil {
+ // Metadata mode: use existing writeAddColumn
+ writeAddColumn(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)
+ } else if colDiff.NewASTNode != nil {
+ // AST-only mode: extract SQL from AST node
+ if err := writeAddColumnFromAST(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewASTNode); err != nil {
+ return "", err
+ }
+ }
}
}
}
@@ -998,8 +1039,17 @@ func generateAlterTableWithOptions(tableDiff *schema.TableDiff, includeColumnAdd
// Alter columns
for _, colDiff := range tableDiff.ColumnChanges {
if colDiff.Action == schema.MetadataDiffActionAlter {
- alterColSQL := generateAlterColumn(tableDiff.SchemaName, tableDiff.TableName, colDiff)
- _, _ = buf.WriteString(alterColSQL)
+ // Support both metadata mode and AST-only mode
+ if colDiff.OldColumn != nil && colDiff.NewColumn != nil {
+ // Metadata mode: use existing generateAlterColumn
+ alterColSQL := generateAlterColumn(tableDiff.SchemaName, tableDiff.TableName, colDiff)
+ _, _ = buf.WriteString(alterColSQL)
+ } else if colDiff.OldASTNode != nil && colDiff.NewASTNode != nil {
+ // AST-only mode: use ALTER COLUMN approach
+ if err := writeAlterColumnFromAST(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldASTNode, colDiff.NewASTNode); err != nil {
+ return "", err
+ }
+ }
}
}
@@ -1026,7 +1076,13 @@ func generateAlterTableWithOptions(tableDiff *schema.TableDiff, includeColumnAdd
}
}
- // Add foreign keys last (they depend on other tables/columns)
+ return buf.String(), nil
+}
+
+// generateAlterTableForeignKeys generates foreign key statements for a table diff
+func generateAlterTableForeignKeys(tableDiff *schema.TableDiff) (string, error) {
+ var buf strings.Builder
+
for _, fkDiff := range tableDiff.ForeignKeyChanges {
if fkDiff.Action == schema.MetadataDiffActionCreate {
if err := writeMigrationForeignKey(&buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.NewForeignKey); err != nil {
@@ -1035,14 +1091,20 @@ func generateAlterTableWithOptions(tableDiff *schema.TableDiff, includeColumnAdd
}
}
- // Add triggers after foreign keys
+ return buf.String(), nil
+}
+
+// generateAlterTableTriggers generates trigger statements for a table diff
+func generateAlterTableTriggers(tableDiff *schema.TableDiff) string {
+ var buf strings.Builder
+
for _, triggerDiff := range tableDiff.TriggerChanges {
if triggerDiff.Action == schema.MetadataDiffActionCreate {
writeMigrationTrigger(&buf, triggerDiff.NewTrigger)
}
}
- return buf.String(), nil
+ return buf.String()
}
func generateAlterColumn(schemaName, tableName string, colDiff *schema.ColumnDiff) string {
@@ -1572,6 +1634,118 @@ func writeAlterColumnDropDefault(out *strings.Builder, schema, table, column str
_, _ = out.WriteString("\n")
}
+// writeAddColumnFromAST writes ALTER TABLE ADD COLUMN statement from AST node
+func writeAddColumnFromAST(out *strings.Builder, schema, table string, columnASTNode pgparser.IColumnDefContext) error {
+ if columnASTNode == nil {
+ return errors.New("Column AST node is nil")
+ }
+
+ columnDefinition := extractColumnDefinitionFromAST(columnASTNode)
+ if columnDefinition == "" {
+ return errors.New("could not extract column definition from AST node")
+ }
+
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD COLUMN `)
+ _, _ = out.WriteString(columnDefinition)
+ _, _ = out.WriteString(";\n")
+
+ return nil
+}
+
+// writeDropColumnFromAST writes ALTER TABLE DROP COLUMN statement from AST node
+func writeDropColumnFromAST(out *strings.Builder, schema, table string, columnASTNode pgparser.IColumnDefContext) error {
+ if columnASTNode == nil {
+ return errors.New("Column AST node is nil")
+ }
+
+ columnName := extractColumnNameFromAST(columnASTNode)
+ if columnName == "" {
+ return errors.New("could not extract column name from AST node")
+ }
+
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" DROP COLUMN IF EXISTS "`)
+ _, _ = out.WriteString(columnName)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+
+ return nil
+}
+
+// writeAlterColumnFromAST writes ALTER TABLE ALTER COLUMN statement from AST nodes
+func writeAlterColumnFromAST(out *strings.Builder, schema, table string, oldColumnASTNode, newColumnASTNode pgparser.IColumnDefContext) error {
+ if oldColumnASTNode == nil || newColumnASTNode == nil {
+ return errors.New("Column AST nodes are nil")
+ }
+
+ // Extract column metadata from both AST nodes (without normalization except for column name)
+ oldMetadata := extractColumnMetadataFromAST(oldColumnASTNode)
+ newMetadata := extractColumnMetadataFromAST(newColumnASTNode)
+
+ if oldMetadata == nil || newMetadata == nil {
+ return errors.New("could not extract column metadata from AST nodes")
+ }
+
+ if oldMetadata.Name == "" {
+ return errors.New("could not extract column name from AST node")
+ }
+
+ // Check for type changes
+ if oldMetadata.Type != newMetadata.Type {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(oldMetadata.Name)
+ _, _ = out.WriteString(`" TYPE `)
+ _, _ = out.WriteString(newMetadata.Type)
+ _, _ = out.WriteString(";\n")
+ }
+
+ // Check for nullable changes
+ if oldMetadata.Nullable != newMetadata.Nullable {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(oldMetadata.Name)
+ if newMetadata.Nullable {
+ _, _ = out.WriteString(`" DROP NOT NULL`)
+ } else {
+ _, _ = out.WriteString(`" SET NOT NULL`)
+ }
+ _, _ = out.WriteString(";\n")
+ }
+
+ // Check for default value changes
+ if oldMetadata.Default != newMetadata.Default {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(oldMetadata.Name)
+ if newMetadata.Default == "" {
+ _, _ = out.WriteString(`" DROP DEFAULT`)
+ } else {
+ _, _ = out.WriteString(`" SET DEFAULT `)
+ _, _ = out.WriteString(newMetadata.Default)
+ }
+ _, _ = out.WriteString(";\n")
+ }
+
+ return nil
+}
+
func writeAddCheckConstraint(out *strings.Builder, schema, table string, check *storepb.CheckConstraintMetadata) {
_, _ = out.WriteString(`ALTER TABLE "`)
_, _ = out.WriteString(schema)
@@ -1759,9 +1933,9 @@ func writeMigrationViewFromAST(out *strings.Builder, astNode any) error {
viewSQL = ctx.GetText()
}
} else {
- // Generic fallback - try to get text directly
- if tree, ok := astNode.(interface{ GetText() string }); ok {
- viewSQL = tree.GetText()
+ // Generic fallback - try to get text using token approach first
+ if tree, ok := astNode.(antlr.ParseTree); ok {
+ viewSQL = getTextFromAST(tree)
}
}
@@ -2581,6 +2755,30 @@ func (v *CreateOrReplaceVisitor) visitCreateFunctionStmt(ctx *pgparser.Createfun
return nil
}
+// extractColumnNameFromAST extracts column name from column definition AST node
+func extractColumnNameFromAST(columnASTNode pgparser.IColumnDefContext) string {
+ if columnASTNode == nil {
+ return ""
+ }
+
+ // Use the proper normalization function for PostgreSQL column identifiers
+ if columnASTNode.Colid() != nil {
+ return pgpluginparser.NormalizePostgreSQLColid(columnASTNode.Colid())
+ }
+
+ return ""
+}
+
+// extractColumnDefinitionFromAST extracts the full column definition from AST node
+func extractColumnDefinitionFromAST(columnASTNode pgparser.IColumnDefContext) string {
+ if columnASTNode == nil {
+ return ""
+ }
+
+ // Use the getTextFromAST helper to extract text properly
+ return getTextFromAST(columnASTNode)
+}
+
// findFunctionToken finds the FUNCTION token in the CREATE FUNCTION statement
func (v *CreateOrReplaceVisitor) findFunctionToken(ctx *pgparser.CreatefunctionstmtContext) antlr.Token {
// Get all tokens in the context range
@@ -2653,9 +2851,9 @@ func getViewDependenciesFromAST(astNode any, schemaName string, fullSchemaMetada
}
}
- // Fallback to GetText() if token stream approach failed
+ // Fallback to token-based approach if token stream approach failed
if selectStatement == "" {
- selectStatement = ctx.Selectstmt().GetText()
+ selectStatement = getTextFromAST(ctx.Selectstmt())
}
}
}
@@ -2714,3 +2912,99 @@ func getViewDependenciesFromAST(astNode any, schemaName string, fullSchemaMetada
return dependencies
}
+
+// extractColumnMetadataFromAST extracts column metadata from AST node without normalization (except column name)
+// This is used in AST-only mode where we need the raw values for comparison
+func extractColumnMetadataFromAST(columnDef pgparser.IColumnDefContext) *columnMetadataAST {
+ if columnDef == nil {
+ return nil
+ }
+
+ // Only normalize the column name - everything else stays as raw text
+ columnName := ""
+ if columnDef.Colid() != nil {
+ columnName = pgpluginparser.NormalizePostgreSQLColid(columnDef.Colid())
+ }
+
+ metadata := &columnMetadataAST{
+ Name: columnName,
+ }
+
+ // Extract type as raw text
+ if columnDef.Typename() != nil {
+ metadata.Type = getTextFromAST(columnDef.Typename())
+ }
+
+ // Extract nullable - check AST directly for NOT NULL constraint
+ metadata.Nullable = true // Default is nullable
+ if columnDef.Colquallist() != nil {
+ for _, qualifier := range columnDef.Colquallist().AllColconstraint() {
+ if qualifier != nil && qualifier.Colconstraintelem() != nil {
+ elem := qualifier.Colconstraintelem()
+ // Check for NOT NULL constraint using AST inspection
+ if elem.NOT() != nil && elem.NULL_P() != nil {
+ metadata.Nullable = false
+ break
+ }
+ // Check for explicit NULL constraint
+ if elem.NULL_P() != nil && elem.NOT() == nil {
+ metadata.Nullable = true
+ }
+ }
+ }
+ }
+
+ // Extract default value using AST inspection
+ if columnDef.Colquallist() != nil {
+ for _, qualifier := range columnDef.Colquallist().AllColconstraint() {
+ if qualifier != nil && qualifier.Colconstraintelem() != nil {
+ elem := qualifier.Colconstraintelem()
+ // Check for DEFAULT constraint using AST inspection
+ if elem.DEFAULT() != nil && elem.B_expr() != nil {
+ metadata.Default = getTextFromAST(elem.B_expr())
+ break
+ }
+ }
+ }
+ }
+
+ return metadata
+}
+
+// columnMetadataAST holds column metadata extracted from AST without normalization
+type columnMetadataAST struct {
+ Name string
+ Type string
+ Nullable bool
+ Default string
+}
+
+// getTextFromAST extracts text from AST node using tokens when available, fallback to GetText()
+func getTextFromAST(ctx antlr.ParseTree) string {
+ if ctx == nil {
+ return ""
+ }
+
+ // Try to get text from tokens first (preferred method)
+ // Check for interfaces that have the required methods
+ type parserContext interface {
+ GetParser() antlr.Parser
+ GetStart() antlr.Token
+ GetStop() antlr.Token
+ }
+
+ if ruleContext, ok := ctx.(parserContext); ok {
+ if parser := ruleContext.GetParser(); parser != nil {
+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {
+ start := ruleContext.GetStart()
+ stop := ruleContext.GetStop()
+ if start != nil && stop != nil {
+ return tokenStream.GetTextFromTokens(start, stop)
+ }
+ }
+ }
+ }
+
+ // Fallback to GetText() if tokens are not available
+ return ctx.GetText()
+}
diff --git a/backend/plugin/schema/pg/get_database_metadata.go b/backend/plugin/schema/pg/get_database_metadata.go
index 6d8ee5de6f..6ff10a2508 100644
--- a/backend/plugin/schema/pg/get_database_metadata.go
+++ b/backend/plugin/schema/pg/get_database_metadata.go
@@ -1591,7 +1591,7 @@ func (e *metadataExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
functionMetadata := &storepb.FunctionMetadata{
Name: funcName,
Definition: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),
- Signature: extractFunctionSignature(ctx, funcName),
+ Signature: ExtractFunctionSignature(ctx, funcName),
}
if schemaMetadata.Functions == nil {
@@ -1600,8 +1600,8 @@ func (e *metadataExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
schemaMetadata.Functions = append(schemaMetadata.Functions, functionMetadata)
}
-// extractFunctionSignature extracts the function signature with parameter types
-func extractFunctionSignature(ctx *parser.CreatefunctionstmtContext, funcName string) string {
+// ExtractFunctionSignature extracts the function signature with parameter types
+func ExtractFunctionSignature(ctx *parser.CreatefunctionstmtContext, funcName string) string {
var signature strings.Builder
signature.WriteString(funcName)
signature.WriteString(`(`)
diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.go
index 44b1a19db0..6bb706b571 100644
--- a/backend/plugin/schema/pg/get_sdl_diff.go
+++ b/backend/plugin/schema/pg/get_sdl_diff.go
@@ -154,7 +154,7 @@ func (l *sdlChunkExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
funcName := strings.Join(funcNameParts, ".")
// Extract function signature for proper identification
- funcSignature := extractFunctionSignature(ctx, funcName)
+ funcSignature := ExtractFunctionSignature(ctx, funcName)
chunk := &schema.SDLChunk{
Identifier: funcSignature, // Use signature instead of name
@@ -231,7 +231,7 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, curren
return errors.Errorf("expected CreatestmtContext for current table %s", currentChunk.Identifier)
}
- columnChanges := processColumnChanges(oldASTNode, newASTNode)
+ columnChanges := processColumnChanges(oldASTNode, newASTNode, currentSchema, previousSchema)
foreignKeyChanges := processForeignKeyChanges(oldASTNode, newASTNode)
checkConstraintChanges := processCheckConstraintChanges(oldASTNode, newASTNode)
primaryKeyChanges := processPrimaryKeyChanges(oldASTNode, newASTNode)
@@ -303,27 +303,36 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, curren
// processColumnChanges analyzes column changes between old and new table definitions
// Following the same pattern as processTableChanges: compare text first, then analyze differences
-func processColumnChanges(oldTable, newTable *parser.CreatestmtContext) []*schema.ColumnDiff {
+// If schemas are nil, operates in AST-only mode without metadata extraction
+func processColumnChanges(oldTable, newTable *parser.CreatestmtContext, currentSchema, previousSchema *model.DatabaseSchema) []*schema.ColumnDiff {
if oldTable == nil || newTable == nil {
return []*schema.ColumnDiff{}
}
+ // Detect AST-only mode: when both schemas are nil, operate without metadata extraction
+ astOnlyMode := currentSchema == nil && previousSchema == nil
+
// Step 1: Extract all column definitions with their AST nodes for text comparison
- oldColumnMap := extractColumnDefinitionsWithAST(oldTable)
- newColumnMap := extractColumnDefinitionsWithAST(newTable)
+ oldColumns := extractColumnDefinitionsWithAST(oldTable)
+ newColumns := extractColumnDefinitionsWithAST(newTable)
var columnDiffs []*schema.ColumnDiff
// Step 2: Process current columns to find created and modified columns
- for columnName, newColumnDef := range newColumnMap {
- if oldColumnDef, exists := oldColumnMap[columnName]; exists {
+ // Use the order from the new table's AST to maintain original column order
+ for _, columnName := range newColumns.Order {
+ newColumnDef := newColumns.Map[columnName]
+ if oldColumnDef, exists := oldColumns.Map[columnName]; exists {
// Column exists in both - check if modified by comparing text first
currentText := getColumnText(newColumnDef.ASTNode)
previousText := getColumnText(oldColumnDef.ASTNode)
if currentText != previousText {
- // Column was modified - only now extract detailed metadata
- oldColumn := extractColumnMetadata(oldColumnDef.ASTNode)
- newColumn := extractColumnMetadata(newColumnDef.ASTNode)
+ // Column was modified - extract metadata only if not in AST-only mode
+ var oldColumn, newColumn *storepb.ColumnMetadata
+ if !astOnlyMode {
+ oldColumn = extractColumnMetadata(oldColumnDef.ASTNode)
+ newColumn = extractColumnMetadata(newColumnDef.ASTNode)
+ }
columnDiffs = append(columnDiffs, &schema.ColumnDiff{
Action: schema.MetadataDiffActionAlter,
@@ -335,8 +344,11 @@ func processColumnChanges(oldTable, newTable *parser.CreatestmtContext) []*schem
}
// If text is identical, skip - no changes detected
} else {
- // New column - extract metadata only for new columns
- newColumn := extractColumnMetadata(newColumnDef.ASTNode)
+ // New column - extract metadata only if not in AST-only mode
+ var newColumn *storepb.ColumnMetadata
+ if !astOnlyMode {
+ newColumn = extractColumnMetadata(newColumnDef.ASTNode)
+ }
columnDiffs = append(columnDiffs, &schema.ColumnDiff{
Action: schema.MetadataDiffActionCreate,
OldColumn: nil,
@@ -348,10 +360,15 @@ func processColumnChanges(oldTable, newTable *parser.CreatestmtContext) []*schem
}
// Step 3: Process previous columns to find dropped columns
- for columnName, oldColumnDef := range oldColumnMap {
- if _, exists := newColumnMap[columnName]; !exists {
- // Column was dropped - extract metadata only for dropped columns
- oldColumn := extractColumnMetadata(oldColumnDef.ASTNode)
+ // Use the order from the old table's AST to maintain original column order
+ for _, columnName := range oldColumns.Order {
+ oldColumnDef := oldColumns.Map[columnName]
+ if _, exists := newColumns.Map[columnName]; !exists {
+ // Column was dropped - extract metadata only if not in AST-only mode
+ var oldColumn *storepb.ColumnMetadata
+ if !astOnlyMode {
+ oldColumn = extractColumnMetadata(oldColumnDef.ASTNode)
+ }
columnDiffs = append(columnDiffs, &schema.ColumnDiff{
Action: schema.MetadataDiffActionDrop,
OldColumn: oldColumn,
@@ -371,13 +388,22 @@ type ColumnDefWithAST struct {
ASTNode parser.IColumnDefContext
}
-// extractColumnDefinitionsWithAST extracts only column name and AST node for text comparison
-// This is more efficient than full metadata extraction when we only need text comparison
-func extractColumnDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*ColumnDefWithAST {
- columns := make(map[string]*ColumnDefWithAST)
+// ColumnDefWithASTOrdered holds column definitions in AST order for deterministic processing
+type ColumnDefWithASTOrdered struct {
+ Map map[string]*ColumnDefWithAST
+ Order []string // Column names in the order they appear in the AST
+}
+
+// extractColumnDefinitionsWithAST extracts column definitions and preserves their AST order
+// This ensures deterministic processing while maintaining the original column order
+func extractColumnDefinitionsWithAST(createStmt *parser.CreatestmtContext) *ColumnDefWithASTOrdered {
+ result := &ColumnDefWithASTOrdered{
+ Map: make(map[string]*ColumnDefWithAST),
+ Order: []string{},
+ }
if createStmt == nil {
- return columns
+ return result
}
// Get the optTableElementList which contains column definitions
@@ -391,16 +417,18 @@ func extractColumnDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[s
if columnDef.Colid() != nil {
columnName := pgparser.NormalizePostgreSQLColid(columnDef.Colid())
- columns[columnName] = &ColumnDefWithAST{
+ result.Map[columnName] = &ColumnDefWithAST{
Name: columnName,
ASTNode: columnDef,
}
+ // Preserve the order columns appear in the AST
+ result.Order = append(result.Order, columnName)
}
}
}
}
- return columns
+ return result
}
// extractColumnMetadata extracts full column metadata from a single column AST node
diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/ddl.sql
index 7dd6c65520..444ec43328 100644
--- a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/ddl.sql
@@ -15,13 +15,13 @@ ALTER TABLE "public"."events" ADD COLUMN "capacities" _int4;
ALTER TABLE "public"."events" ADD COLUMN "locations" _text DEFAULT ARRAY[]::TEXT[] NOT NULL;
ALTER TABLE "public"."events" ADD COLUMN "metadata" _jsonb DEFAULT ARRAY[]::JSONB[];
ALTER TABLE "public"."events" ADD COLUMN "schedules" _timestamp;
-ALTER TABLE "public"."products" ADD COLUMN "features" _jsonb;
-ALTER TABLE "public"."products" ADD COLUMN "ratings" _int4 DEFAULT ARRAY[0,0,0,0,0];
-ALTER TABLE "public"."products" ADD COLUMN "variants" _text;
ALTER TABLE "public"."events" ALTER COLUMN "event_dates" TYPE _timestamptz;
CREATE INDEX idx_events_locations ON public.events USING gin (locations);
CREATE INDEX idx_events_participants ON public.events USING gin (participant_ids);
+ALTER TABLE "public"."products" ADD COLUMN "features" _jsonb;
+ALTER TABLE "public"."products" ADD COLUMN "ratings" _int4 DEFAULT ARRAY[0,0,0,0,0];
+ALTER TABLE "public"."products" ADD COLUMN "variants" _text;
ALTER TABLE "public"."products" ALTER COLUMN "category_ids" TYPE _int8;
ALTER TABLE "public"."products" ALTER COLUMN "tags" SET DEFAULT ARRAY[]::TEXT[];
CREATE INDEX idx_products_categories ON public.products USING gin (category_ids);
diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/ddl.sql
index f234db9a27..06bc94918b 100644
--- a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/ddl.sql
@@ -1,6 +1,9 @@
ALTER TABLE "public"."documents" ADD COLUMN "checksum" bytea;
ALTER TABLE "public"."documents" ADD COLUMN "file_info" jsonb DEFAULT '{}';
ALTER TABLE "public"."documents" ADD COLUMN "updated_at" timestamp(6) without time zone;
+ALTER TABLE "public"."documents" ALTER COLUMN "metadata" TYPE jsonb;
+CREATE INDEX idx_documents_metadata ON public.documents USING gin (metadata);
+
CREATE TABLE "public"."files" (
"file_id" uuid NOT NULL DEFAULT gen_random_uuid(),
"filename" character varying(255) NOT NULL,
@@ -16,9 +19,6 @@ CREATE INDEX idx_files_mime_type ON public.files USING btree (mime_type);
ALTER TABLE "public"."sessions" ADD COLUMN "last_accessed" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE "public"."sessions" ADD COLUMN "settings" jsonb DEFAULT '{"theme": "default"}'::jsonb;
-ALTER TABLE "public"."documents" ALTER COLUMN "metadata" TYPE jsonb;
-CREATE INDEX idx_documents_metadata ON public.documents USING gin (metadata);
-
ALTER TABLE "public"."sessions" ALTER COLUMN "session_id" SET DEFAULT gen_random_uuid();
CREATE INDEX idx_sessions_data ON public.sessions USING gin (data);
CREATE INDEX idx_sessions_settings ON public.sessions USING gin (settings);
diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/ddl.sql
index bc25c4b141..770907d80e 100644
--- a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/ddl.sql
@@ -5,6 +5,11 @@ ALTER TABLE "public"."bookings" ADD COLUMN "booking_dates" daterange NOT NULL;
ALTER TABLE "public"."bookings" ADD COLUMN "discount_range" numrange DEFAULT '[0,100)'::NUMRANGE;
ALTER TABLE "public"."bookings" ADD COLUMN "duration_range" int8range;
ALTER TABLE "public"."bookings" ADD COLUMN "valid_periods" _tstzrange;
+ALTER TABLE "public"."bookings" ALTER COLUMN "booking_period" SET NOT NULL;
+CREATE INDEX idx_bookings_dates ON public.bookings USING gist (booking_dates);
+CREATE INDEX idx_bookings_period ON public.bookings USING gist (booking_period);
+CREATE INDEX idx_bookings_price ON public.bookings USING gist (price_range);
+
CREATE TABLE "public"."permissions_matrix" (
"permission_id" integer NOT NULL DEFAULT nextval('public.permissions_matrix_permission_id_seq'::regclass),
"user_role" character varying(50) NOT NULL,
@@ -31,11 +36,6 @@ CREATE INDEX idx_scheduling_dates ON public.scheduling USING gin (available_date
ALTER TABLE "public"."system_flags" ADD COLUMN "access_mask" bit(64);
ALTER TABLE "public"."system_flags" ADD COLUMN "feature_flags" bit(32) DEFAULT B'00000000000000000000000000000000';
ALTER TABLE "public"."system_flags" ADD COLUMN "system_state" bit(128);
-ALTER TABLE "public"."bookings" ALTER COLUMN "booking_period" SET NOT NULL;
-CREATE INDEX idx_bookings_dates ON public.bookings USING gist (booking_dates);
-CREATE INDEX idx_bookings_period ON public.bookings USING gist (booking_period);
-CREATE INDEX idx_bookings_price ON public.bookings USING gist (price_range);
-
ALTER TABLE "public"."system_flags" ALTER COLUMN "bit_flags" TYPE bit(16);
ALTER TABLE "public"."system_flags" ALTER COLUMN "bit_flags" SET NOT NULL;
ALTER TABLE "public"."system_flags" ALTER COLUMN "bit_flags" SET DEFAULT B'0000000000000000';
diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/ddl.sql
index e34e5b0ce8..3cf22ab651 100644
--- a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/ddl.sql
@@ -20,10 +20,17 @@ ALTER TABLE "public"."locations" ADD COLUMN "center_point" point;
ALTER TABLE "public"."locations" ADD COLUMN "coverage_polygon" polygon;
ALTER TABLE "public"."locations" ADD COLUMN "route_path" path;
ALTER TABLE "public"."locations" ADD COLUMN "service_area" circle;
+ALTER TABLE "public"."locations" ALTER COLUMN "coordinates" SET NOT NULL;
+CREATE INDEX idx_locations_boundary ON public.locations USING gist (boundary_box);
+CREATE INDEX idx_locations_coordinates ON public.locations USING gist (coordinates);
+
ALTER TABLE "public"."network_devices" ADD COLUMN "backup_mac" macaddr;
ALTER TABLE "public"."network_devices" ADD COLUMN "gateway" inet;
ALTER TABLE "public"."network_devices" ADD COLUMN "network_range" cidr;
ALTER TABLE "public"."network_devices" ADD COLUMN "subnet_mask" inet;
+ALTER TABLE "public"."network_devices" ALTER COLUMN "ip_address" SET NOT NULL;
+ALTER TABLE "public"."network_devices" ADD CONSTRAINT "network_devices_mac_address_key" UNIQUE (mac_address);
+
CREATE TABLE "public"."network_topology" (
"topology_id" integer NOT NULL DEFAULT nextval('public.network_topology_topology_id_seq'::regclass),
"network_name" character varying(100) NOT NULL,
@@ -36,10 +43,3 @@ CREATE TABLE "public"."network_topology" (
ALTER TABLE "public"."network_topology" ADD CONSTRAINT "network_topology_pkey" PRIMARY KEY (topology_id);
ALTER TABLE "public"."network_topology" ADD CONSTRAINT "network_topology_network_cidr_key" UNIQUE (network_cidr);
-ALTER TABLE "public"."locations" ALTER COLUMN "coordinates" SET NOT NULL;
-CREATE INDEX idx_locations_boundary ON public.locations USING gist (boundary_box);
-CREATE INDEX idx_locations_coordinates ON public.locations USING gist (coordinates);
-
-ALTER TABLE "public"."network_devices" ALTER COLUMN "ip_address" SET NOT NULL;
-ALTER TABLE "public"."network_devices" ADD CONSTRAINT "network_devices_mac_address_key" UNIQUE (mac_address);
-
diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/ddl.sql
index 899e747ce0..430d56baff 100644
--- a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/ddl.sql
@@ -2,10 +2,6 @@ ALTER TABLE "public"."orders" ADD COLUMN "customer_phone" character varying(20);
ALTER TABLE "public"."orders" ADD COLUMN "notes" text;
ALTER TABLE "public"."orders" ADD COLUMN "shipping_address" jsonb;
ALTER TABLE "public"."orders" ADD COLUMN "tax_amount" numeric(15,4) DEFAULT 0.0000;
-ALTER TABLE "public"."products" ADD COLUMN "dimensions" jsonb;
-ALTER TABLE "public"."products" ADD COLUMN "tags" _text;
-ALTER TABLE "public"."products" ADD COLUMN "updated_at" timestamp(6) with time zone;
-ALTER TABLE "public"."products" ADD COLUMN "weight" numeric(6,3);
ALTER TABLE "public"."orders" ALTER COLUMN "customer_email" TYPE character varying(150);
ALTER TABLE "public"."orders" ALTER COLUMN "order_date" TYPE timestamp(6) with time zone;
ALTER TABLE "public"."orders" ALTER COLUMN "order_date" DROP DEFAULT;
@@ -16,6 +12,10 @@ ALTER TABLE "public"."orders" ALTER COLUMN "status" SET DEFAULT 'pending';
ALTER TABLE "public"."orders" ALTER COLUMN "total_amount" TYPE numeric(15,4);
CREATE INDEX idx_orders_status ON public.orders USING btree (status);
+ALTER TABLE "public"."products" ADD COLUMN "dimensions" jsonb;
+ALTER TABLE "public"."products" ADD COLUMN "tags" _text;
+ALTER TABLE "public"."products" ADD COLUMN "updated_at" timestamp(6) with time zone;
+ALTER TABLE "public"."products" ADD COLUMN "weight" numeric(6,3);
ALTER TABLE "public"."products" ALTER COLUMN "category_ids" TYPE _int8;
ALTER TABLE "public"."products" ALTER COLUMN "created_at" TYPE timestamp(6) with time zone;
ALTER TABLE "public"."products" ALTER COLUMN "created_at" SET DEFAULT CURRENT_TIMESTAMP;
diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/ddl.sql
index 0e9d27df2a..b1ee4f2caa 100644
--- a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/ddl.sql
@@ -1,19 +1,4 @@
CREATE SEQUENCE "public"."precision_test_test_id_seq" START WITH 1 INCREMENT BY 1;
-CREATE TABLE "public"."precision_test" (
- "test_id" integer NOT NULL DEFAULT nextval('public.precision_test_test_id_seq'::regclass),
- "expand_varchar" character varying(500),
- "reduce_varchar" character varying(25),
- "expand_numeric" numeric(25,10),
- "reduce_numeric" numeric(4,1),
- "expand_char" character(50),
- "reduce_char" character(5),
- "expand_bits" bit(128),
- "reduce_bits" bit(4),
- "expand_varbits" bit varying(256),
- "reduce_varbits" bit varying(8)
-);
-ALTER TABLE "public"."precision_test" ADD CONSTRAINT "precision_test_pkey" PRIMARY KEY (test_id);
-
ALTER TABLE "public"."data_samples" ALTER COLUMN "bit_flags" TYPE bit(32);
ALTER TABLE "public"."data_samples" ALTER COLUMN "bit_flags" DROP DEFAULT;
ALTER TABLE "public"."data_samples" ALTER COLUMN "bit_flags" SET DEFAULT B'00000000000000000000000000000000';
@@ -35,3 +20,18 @@ ALTER TABLE "public"."measurements" ALTER COLUMN "status_bits" TYPE bit(64);
ALTER TABLE "public"."measurements" ALTER COLUMN "value_high_precision" TYPE numeric(20,12);
ALTER TABLE "public"."measurements" ALTER COLUMN "value_low_precision" TYPE numeric(6,2);
+CREATE TABLE "public"."precision_test" (
+ "test_id" integer NOT NULL DEFAULT nextval('public.precision_test_test_id_seq'::regclass),
+ "expand_varchar" character varying(500),
+ "reduce_varchar" character varying(25),
+ "expand_numeric" numeric(25,10),
+ "reduce_numeric" numeric(4,1),
+ "expand_char" character(50),
+ "reduce_char" character(5),
+ "expand_bits" bit(128),
+ "reduce_bits" bit(4),
+ "expand_varbits" bit varying(256),
+ "reduce_varbits" bit varying(8)
+);
+ALTER TABLE "public"."precision_test" ADD CONSTRAINT "precision_test_pkey" PRIMARY KEY (test_id);
+
diff --git a/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_column_foreign_keys/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_column_foreign_keys/ddl.sql
index 2c0d07b267..a8d0f990f2 100644
--- a/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_column_foreign_keys/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_column_foreign_keys/ddl.sql
@@ -1,6 +1,7 @@
ALTER TABLE "public"."posts" ALTER COLUMN "author_id" SET NOT NULL;
CREATE INDEX idx_posts_author_id ON public.posts USING btree (author_id);
CREATE INDEX idx_posts_category_id ON public.posts USING btree (category_id);
+
ALTER TABLE "public"."posts" ADD CONSTRAINT "fk_posts_author" FOREIGN KEY ("author_id") REFERENCES "public"."users" ("id") ON UPDATE NO ACTION ON DELETE CASCADE;
ALTER TABLE "public"."posts" ADD CONSTRAINT "fk_posts_category" FOREIGN KEY ("category_id") REFERENCES "public"."categories" ("id") ON UPDATE NO ACTION ON DELETE SET NULL;
diff --git a/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_simple_columns/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_simple_columns/ddl.sql
index 84edefe571..3b934d6c1b 100644
--- a/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_simple_columns/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/add_simple_columns/ddl.sql
@@ -2,3 +2,4 @@ ALTER TABLE "public"."products" ADD COLUMN "category" character varying(50) DEFA
ALTER TABLE "public"."products" ADD COLUMN "created_at" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE "public"."products" ADD COLUMN "description" text;
ALTER TABLE "public"."products" ADD COLUMN "is_featured" boolean DEFAULT false;
+
diff --git a/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/complex_column_operations/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/complex_column_operations/ddl.sql
index 9aa5c010c5..485364f1ef 100644
--- a/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/complex_column_operations/ddl.sql
+++ b/backend/plugin/schema/pg/sdl_testdata/table_operations/column_operations/complex_column_operations/ddl.sql
@@ -17,5 +17,6 @@ CREATE INDEX idx_products_category_id ON public.products USING btree (category_i
CREATE INDEX idx_products_name ON public.products USING btree (name);
CREATE INDEX idx_products_price ON public.products USING btree (price);
ALTER TABLE "public"."products" ADD CONSTRAINT "products_price_check" CHECK (price > 0);
+
ALTER TABLE "public"."products" ADD CONSTRAINT "fk_products_category" FOREIGN KEY ("category_id") REFERENCES "public"."categories" ("id") ON UPDATE NO ACTION ON DELETE RESTRICT;