Skip to content

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

feat: generate func/procedure migration for pg sdl diff (#17438)

rebelice338f0dc863d2
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.go
index ebfe63ebd9..09564a76f4 100644
--- a/backend/plugin/schema/differ.go
+++ b/backend/plugin/schema/differ.go
@@ -357,10 +357,15 @@ func addNewSchemaObjects(diff *MetadataDiff, schemaName string, schema *model.Sc
// Add all functions
for _, function := range schema.ListFunctions() {
if !function.GetProto().GetSkipDump() {
+ // Use signature if available, otherwise fall back to name
+ functionName := function.GetProto().Signature
+ if functionName == "" {
+ functionName = function.GetProto().Name
+ }
diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
Action: MetadataDiffActionCreate,
SchemaName: schemaName,
- FunctionName: function.GetProto().Name,
+ FunctionName: functionName,
NewFunction: function.GetProto(),
})
}
@@ -1631,10 +1636,15 @@ func compareFunctions(engine storepb.Engine, diff *MetadataDiff, schemaName stri
// Check for dropped functions
for sig, oldFunc := range oldFuncsBySignature {
if _, exists := newFuncsBySignature[sig]; !exists {
+ // Use signature if available, otherwise fall back to name
+ functionName := oldFunc.GetProto().Signature
+ if functionName == "" {
+ functionName = oldFunc.GetProto().Name
+ }
diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
Action: MetadataDiffActionDrop,
SchemaName: schemaName,
- FunctionName: oldFunc.GetProto().Name,
+ FunctionName: functionName,
OldFunction: oldFunc.GetProto(),
})
}
@@ -1644,10 +1654,15 @@ func compareFunctions(engine storepb.Engine, diff *MetadataDiff, schemaName stri
for sig, newFunc := range newFuncsBySignature {
oldFunc, exists := oldFuncsBySignature[sig]
if !exists {
+ // Use signature if available, otherwise fall back to name
+ functionName := newFunc.GetProto().Signature
+ if functionName == "" {
+ functionName = newFunc.GetProto().Name
+ }
diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
Action: MetadataDiffActionCreate,
SchemaName: schemaName,
- FunctionName: newFunc.GetProto().Name,
+ FunctionName: functionName,
NewFunction: newFunc.GetProto(),
})
} else {
@@ -1661,10 +1676,15 @@ func compareFunctions(engine storepb.Engine, diff *MetadataDiff, schemaName stri
// Determine the action based on the comparison result
if comparison.CanUseAlterFunction {
// Use ALTER FUNCTION for body-only changes
+ // Use signature if available, otherwise fall back to name
+ functionName := oldFunc.GetProto().Signature
+ if functionName == "" {
+ functionName = oldFunc.GetProto().Name
+ }
diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
Action: MetadataDiffActionAlter,
SchemaName: schemaName,
- FunctionName: oldFunc.GetProto().Name,
+ FunctionName: functionName,
OldFunction: oldFunc.GetProto(),
NewFunction: newFunc.GetProto(),
SignatureChanged: comparison.SignatureChanged,
@@ -1675,10 +1695,20 @@ func compareFunctions(engine storepb.Engine, diff *MetadataDiff, schemaName stri
})
} else {
// Use DROP and CREATE for signature changes
+ // Use signature if available, otherwise fall back to name for DROP
+ oldFunctionName := oldFunc.GetProto().Signature
+ if oldFunctionName == "" {
+ oldFunctionName = oldFunc.GetProto().Name
+ }
+ // Use signature if available, otherwise fall back to name for CREATE
+ newFunctionName := newFunc.GetProto().Signature
+ if newFunctionName == "" {
+ newFunctionName = newFunc.GetProto().Name
+ }
diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
Action: MetadataDiffActionDrop,
SchemaName: schemaName,
- FunctionName: oldFunc.GetProto().Name,
+ FunctionName: oldFunctionName,
OldFunction: oldFunc.GetProto(),
SignatureChanged: comparison.SignatureChanged,
BodyChanged: comparison.BodyChanged,
@@ -1689,7 +1719,7 @@ func compareFunctions(engine storepb.Engine, diff *MetadataDiff, schemaName stri
diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
Action: MetadataDiffActionCreate,
SchemaName: schemaName,
- FunctionName: newFunc.GetProto().Name,
+ FunctionName: newFunctionName,
NewFunction: newFunc.GetProto(),
SignatureChanged: comparison.SignatureChanged,
BodyChanged: comparison.BodyChanged,
diff --git a/backend/plugin/schema/pg/chunk_extraction_test.go b/backend/plugin/schema/pg/chunk_extraction_test.go
index df08261a79..ff3cfb34bc 100644
--- a/backend/plugin/schema/pg/chunk_extraction_test.go
+++ b/backend/plugin/schema/pg/chunk_extraction_test.go
@@ -58,7 +58,7 @@ BEGIN
END;
$$ LANGUAGE plpgsql;`,
expectedResults: map[string]string{
- "FUNCTION:get_user_count": `CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$
+ "FUNCTION:get_user_count()": `CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$
BEGIN
RETURN (SELECT COUNT(*) FROM users);
END;
@@ -107,7 +107,7 @@ SELECT id, name, price
FROM products
WHERE price > 0`,
"INDEX:idx_products_price": `CREATE INDEX idx_products_price ON products(price)`,
- "FUNCTION:calculate_discount": `CREATE FUNCTION calculate_discount(amount DECIMAL) RETURNS DECIMAL AS $$
+ "FUNCTION:calculate_discount(amount numeric)": `CREATE FUNCTION calculate_discount(amount DECIMAL) RETURNS DECIMAL AS $$
BEGIN
RETURN amount * 0.9;
END;
diff --git a/backend/plugin/schema/pg/function_migration_integration_test.go b/backend/plugin/schema/pg/function_migration_integration_test.go
new file mode 100644
index 0000000000..82ba9ad151
--- /dev/null
+++ b/backend/plugin/schema/pg/function_migration_integration_test.go
@@ -0,0 +1,386 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+)
+
+func TestFunctionSDLDiffAndMigrationIntegration(t *testing.T) {
+ tests := []struct {
+ name string
+ previousSDL string
+ currentSDL string
+ expectedMigration string
+ }{
+ {
+ name: "Create new function",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedMigration: `CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+
+`,
+ },
+ {
+ name: "Drop function",
+ previousSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: ``,
+ expectedMigration: `DROP FUNCTION IF EXISTS "public"."calculate_area"(radius numeric);
+`,
+ },
+ {
+ name: "Modify function (CREATE OR REPLACE)",
+ previousSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159 * radius * radius;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159265 * radius * radius; -- More precise PI
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedMigration: `CREATE OR REPLACE FUNCTION calculate_area(radius DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN 3.14159265 * radius * radius; -- More precise PI
+ END;
+ $$ LANGUAGE plpgsql;
+
+`,
+ },
+ {
+ name: "Create new procedure (stored as function)",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ -- Some procedure logic here
+ NULL;
+ END;
+ $$;
+ `,
+ expectedMigration: `CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ -- Some procedure logic here
+ NULL;
+ END;
+ $$;
+
+`,
+ },
+ {
+ name: "Overloaded functions with different signatures",
+ previousSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION add_numbers(a FLOAT, b FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedMigration: `CREATE FUNCTION add_numbers(a FLOAT, b FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+
+`,
+ },
+ {
+ name: "Drop one overloaded function",
+ previousSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION add_numbers(a FLOAT, b FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN a + b;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedMigration: `DROP FUNCTION IF EXISTS "public"."add_numbers"(a float, b float);
+`,
+ },
+ {
+ name: "Modify one overloaded function",
+ previousSDL: `
+ CREATE FUNCTION calculate(x INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN x * 2;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION calculate(x FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN x * 2.0;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE FUNCTION calculate(x INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN x * 3; -- Changed logic
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION calculate(x FLOAT)
+ RETURNS FLOAT AS $$
+ BEGIN
+ RETURN x * 2.0;
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedMigration: `CREATE OR REPLACE FUNCTION calculate(x INTEGER)
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN x * 3; -- Changed logic
+ END;
+ $$ LANGUAGE plpgsql;
+
+`,
+ },
+ }
+
+ 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 function changes with AST nodes
+ if len(diff.FunctionChanges) > 0 {
+ for _, funcDiff := range diff.FunctionChanges {
+ switch funcDiff.Action {
+ case schema.MetadataDiffActionCreate:
+ assert.NotNil(t, funcDiff.NewASTNode,
+ "Create action should have NewASTNode")
+ assert.Nil(t, funcDiff.OldASTNode,
+ "Create action should not have OldASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, funcDiff.NewFunction,
+ "AST-only mode should not have metadata")
+ case schema.MetadataDiffActionDrop:
+ assert.NotNil(t, funcDiff.OldASTNode,
+ "Drop action should have OldASTNode")
+ assert.Nil(t, funcDiff.NewASTNode,
+ "Drop action should not have NewASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, funcDiff.OldFunction,
+ "AST-only mode should not have metadata")
+ case schema.MetadataDiffActionAlter:
+ assert.NotNil(t, funcDiff.OldASTNode,
+ "Alter action should have OldASTNode")
+ assert.NotNil(t, funcDiff.NewASTNode,
+ "Alter action should have NewASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, funcDiff.OldFunction,
+ "AST-only mode should not have metadata")
+ assert.Nil(t, funcDiff.NewFunction,
+ "AST-only mode should not have metadata")
+ default:
+ // Other actions
+ t.Logf("Encountered function action: %v", funcDiff.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 functions
+ if tt.expectedMigration != "" {
+ if containsString(tt.expectedMigration, "CREATE FUNCTION") {
+ assert.Contains(t, migrationSQL, "CREATE FUNCTION",
+ "Migration should contain CREATE FUNCTION statement")
+ }
+ if containsString(tt.expectedMigration, "CREATE PROCEDURE") {
+ assert.Contains(t, migrationSQL, "CREATE PROCEDURE",
+ "Migration should contain CREATE PROCEDURE statement")
+ }
+ if containsString(tt.expectedMigration, "DROP FUNCTION") {
+ assert.Contains(t, migrationSQL, "DROP FUNCTION",
+ "Migration should contain DROP FUNCTION statement")
+ }
+ }
+ })
+ }
+}
+
+func TestFunctionMigrationASTOnlyModeValidation(t *testing.T) {
+ // Test that ensures AST-only mode works correctly without any metadata extraction
+ previousSDL := ``
+ currentSDL := `
+ CREATE FUNCTION get_total(amount DECIMAL) RETURNS DECIMAL AS $$
+ BEGIN
+ RETURN amount * 1.1;
+ END;
+ $$ LANGUAGE plpgsql;
+ `
+
+ // Get diff without metadata extraction
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Should have exactly one function change
+ assert.Len(t, diff.FunctionChanges, 1)
+ funcDiff := diff.FunctionChanges[0]
+
+ // Verify AST-only mode properties
+ assert.Equal(t, schema.MetadataDiffActionCreate, funcDiff.Action)
+ assert.Equal(t, "public", funcDiff.SchemaName)
+ assert.Equal(t, "get_total(amount numeric)", funcDiff.FunctionName)
+
+ // Critical assertion: No metadata should be present (AST-only mode)
+ assert.Nil(t, funcDiff.NewFunction, "AST-only mode should not extract metadata")
+ assert.Nil(t, funcDiff.OldFunction, "AST-only mode should not extract metadata")
+
+ // But AST nodes should be present
+ assert.NotNil(t, funcDiff.NewASTNode, "AST node should be present for CREATE action")
+ assert.Nil(t, funcDiff.OldASTNode, "No old AST node for CREATE action")
+
+ // Generate migration should work with AST nodes only
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+ assert.Contains(t, migrationSQL, "CREATE FUNCTION get_total(amount DECIMAL) RETURNS DECIMAL")
+}
+
+func TestOverloadedFunctionSignatureHandling(t *testing.T) {
+ // Test that verifies signature-based identification works correctly in full flow
+ previousSDL := ``
+ currentSDL := `
+ -- Create two functions with same name but different signatures
+ CREATE FUNCTION format_value(val INTEGER)
+ RETURNS TEXT AS $$
+ BEGIN
+ RETURN val::TEXT;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE FUNCTION format_value(val DECIMAL, precision_digits INTEGER)
+ RETURNS TEXT AS $$
+ BEGIN
+ RETURN ROUND(val, precision_digits)::TEXT;
+ END;
+ $$ LANGUAGE plpgsql;
+ `
+
+ // Get diff without metadata extraction (AST-only mode)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Should have exactly two function changes (CREATE actions)
+ assert.Len(t, diff.FunctionChanges, 2)
+
+ // Verify both functions are CREATE actions with different signatures
+ createCount := 0
+ signatures := make(map[string]bool)
+ for _, funcDiff := range diff.FunctionChanges {
+ if funcDiff.Action == schema.MetadataDiffActionCreate {
+ createCount++
+ // Verify AST-only mode properties
+ assert.NotNil(t, funcDiff.NewASTNode, "AST node should be present for CREATE action")
+ assert.Nil(t, funcDiff.OldASTNode, "No old AST node for CREATE action")
+ assert.Nil(t, funcDiff.NewFunction, "AST-only mode should not extract metadata")
+
+ // Collect signatures to verify they're different
+ signatures[funcDiff.FunctionName] = true
+ }
+ }
+ assert.Equal(t, 2, createCount, "Should have two CREATE actions")
+
+ // Verify the signatures are different
+ assert.Len(t, signatures, 2, "Should have two different function signatures")
+
+ // Expected signatures
+ expectedSignatures := map[string]bool{
+ "format_value(val integer)": true,
+ "format_value(val numeric, precision_digits integer)": true,
+ }
+ assert.Equal(t, expectedSignatures, signatures, "Should have correct function signatures")
+
+ // Generate migration SQL - this should work with both functions
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+ assert.NotEmpty(t, migrationSQL, "Migration SQL should not be empty")
+
+ // Verify the migration contains both functions
+ assert.Contains(t, migrationSQL, "format_value(val INTEGER)")
+ assert.Contains(t, migrationSQL, "format_value(val DECIMAL, precision_digits INTEGER)")
+
+ // Verify both functions are created
+ functionCount := strings.Count(migrationSQL, "CREATE FUNCTION format_value")
+ assert.Equal(t, 2, functionCount, "Should create both overloaded functions")
+}
+
+// Helper function to check if a string contains a substring
+func containsString(s, substr string) bool {
+ return strings.Contains(s, substr)
+}
diff --git a/backend/plugin/schema/pg/function_sdl_diff_test.go b/backend/plugin/schema/pg/function_sdl_diff_test.go
index f96880b9f3..dab53a1124 100644
--- a/backend/plugin/schema/pg/function_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/function_sdl_diff_test.go
@@ -61,7 +61,7 @@ func TestFunctionSDLDiff(t *testing.T) {
expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop},
},
{
- name: "Modify function (drop and recreate)",
+ name: "Modify function (CREATE OR REPLACE)",
previousSDL: `
CREATE TABLE users (
id SERIAL PRIMARY KEY,
@@ -90,8 +90,8 @@ func TestFunctionSDLDiff(t *testing.T) {
END;
$$ LANGUAGE plpgsql;
`,
- expectedFunctionChanges: 2, // Drop + Create
- expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop, schema.MetadataDiffActionCreate},
+ expectedFunctionChanges: 1, // ALTER only
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionAlter},
},
{
name: "No changes to function",
@@ -268,6 +268,11 @@ func TestFunctionSDLDiff(t *testing.T) {
"Function diff %d should have OldASTNode for DROP action", i)
assert.Nil(t, funcDiff.NewASTNode,
"Function diff %d should not have NewASTNode for DROP action", i)
+ case schema.MetadataDiffActionAlter:
+ assert.NotNil(t, funcDiff.OldASTNode,
+ "Function diff %d should have OldASTNode for ALTER action", i)
+ assert.NotNil(t, funcDiff.NewASTNode,
+ "Function diff %d should have NewASTNode for ALTER action", i)
default:
t.Errorf("Unexpected action %v for function diff %d", funcDiff.Action, i)
}
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.go
index dfb0f866b6..277b1099f3 100644
--- a/backend/plugin/schema/pg/generate_migration.go
+++ b/backend/plugin/schema/pg/generate_migration.go
@@ -1137,8 +1137,24 @@ func writeDropFunction(out *strings.Builder, schema, function string) {
_, _ = out.WriteString(`DROP FUNCTION IF EXISTS "`)
_, _ = out.WriteString(schema)
_, _ = out.WriteString(`"."`)
- _, _ = out.WriteString(function)
- _, _ = out.WriteString(`";`)
+
+ // Parse function signature to extract function name and parameters
+ // Format: function_name(param1 type1, param2 type2)
+ parenIndex := strings.Index(function, "(")
+ if parenIndex > 0 {
+ // Extract function name and parameters separately
+ funcName := function[:parenIndex]
+ params := function[parenIndex:] // includes parentheses
+ _, _ = out.WriteString(funcName)
+ _, _ = out.WriteString(`"`)
+ _, _ = out.WriteString(params)
+ } else {
+ // Fallback for functions without parameters
+ _, _ = out.WriteString(function)
+ _, _ = out.WriteString(`"()`)
+ }
+
+ _, _ = out.WriteString(`;`)
_, _ = out.WriteString("\n")
}
@@ -1459,19 +1475,29 @@ func writeAddCheckConstraint(out *strings.Builder, schema, table string, check *
func writeFunctionDiff(out *strings.Builder, funcDiff *schema.FunctionDiff) error {
switch funcDiff.Action {
case schema.MetadataDiffActionCreate:
- // CREATE new function
- _, _ = out.WriteString(funcDiff.NewFunction.Definition)
- if !strings.HasSuffix(strings.TrimSpace(funcDiff.NewFunction.Definition), ";") {
- _, _ = out.WriteString(";")
+ // CREATE new function - support both metadata and AST-only modes
+ if funcDiff.NewFunction != nil {
+ // Metadata mode: use function definition
+ _, _ = out.WriteString(funcDiff.NewFunction.Definition)
+ if !strings.HasSuffix(strings.TrimSpace(funcDiff.NewFunction.Definition), ";") {
+ _, _ = out.WriteString(";")
+ }
+ _, _ = out.WriteString("\n\n")
+ } else if funcDiff.NewASTNode != nil {
+ // AST-only mode: extract SQL from AST node
+ if err := writeMigrationFunctionFromAST(out, funcDiff.NewASTNode); err != nil {
+ return err
+ }
+ } else {
+ return errors.Errorf("function diff for %s.%s has neither metadata nor AST node", funcDiff.SchemaName, funcDiff.FunctionName)
}
- _, _ = out.WriteString("\n\n")
case schema.MetadataDiffActionAlter:
// ALTER function using CREATE OR REPLACE
// The decision to use ALTER vs DROP/CREATE was already made in differ.go
// If we reach here, it means we can safely use CREATE OR REPLACE
if funcDiff.NewFunction != nil {
- // Use ANTLR parser to safely convert CREATE FUNCTION to CREATE OR REPLACE FUNCTION
+ // Metadata mode: use ANTLR parser to safely convert CREATE FUNCTION to CREATE OR REPLACE FUNCTION
definition := convertToCreateOrReplace(funcDiff.NewFunction.Definition)
_, _ = out.WriteString(definition)
@@ -1479,6 +1505,13 @@ func writeFunctionDiff(out *strings.Builder, funcDiff *schema.FunctionDiff) erro
_, _ = out.WriteString(";")
}
_, _ = out.WriteString("\n\n")
+ } else if funcDiff.NewASTNode != nil {
+ // AST-only mode: extract SQL and convert to CREATE OR REPLACE
+ if err := writeMigrationFunctionFromASTWithReplace(out, funcDiff.NewASTNode); err != nil {
+ return err
+ }
+ } else {
+ return errors.Errorf("function diff for %s.%s has neither metadata nor AST node", funcDiff.SchemaName, funcDiff.FunctionName)
}
default:
@@ -1646,6 +1679,93 @@ func writeMigrationView(out *strings.Builder, schema string, view *storepb.ViewM
return nil
}
+// writeMigrationFunctionFromAST writes a CREATE FUNCTION statement from AST node
+func writeMigrationFunctionFromAST(out *strings.Builder, astNode any) error {
+ if astNode == nil {
+ return errors.New("AST node is nil")
+ }
+
+ // Extract the original SQL text from the AST node
+ var functionSQL string
+
+ // Try to cast to PostgreSQL CreatefunctionstmtContext first
+ if ctx, ok := astNode.(*pgparser.CreatefunctionstmtContext); ok {
+ // First try to get text using token stream
+ if tokenStream := ctx.GetParser().GetTokenStream(); tokenStream != nil {
+ start := ctx.GetStart()
+ stop := ctx.GetStop()
+ if start != nil && stop != nil {
+ functionSQL = tokenStream.GetTextFromTokens(start, stop)
+ }
+ }
+
+ // Fallback to GetText() if token stream approach failed
+ if functionSQL == "" {
+ functionSQL = ctx.GetText()
+ }
+ } else {
+ return errors.Errorf("unsupported AST node type for function: %T", astNode)
+ }
+
+ if functionSQL == "" {
+ return errors.New("could not extract function SQL from AST node")
+ }
+
+ // Write the function SQL
+ _, _ = out.WriteString(functionSQL)
+ if !strings.HasSuffix(strings.TrimSpace(functionSQL), ";") {
+ _, _ = out.WriteString(";")
+ }
+ _, _ = out.WriteString("\n\n")
+
+ return nil
+}
+
+// writeMigrationFunctionFromASTWithReplace writes a CREATE OR REPLACE FUNCTION statement from AST node
+func writeMigrationFunctionFromASTWithReplace(out *strings.Builder, astNode any) error {
+ if astNode == nil {
+ return errors.New("AST node is nil")
+ }
+
+ // Extract the original SQL text from the AST node
+ var functionSQL string
+
+ // Try to cast to PostgreSQL CreatefunctionstmtContext first
+ if ctx, ok := astNode.(*pgparser.CreatefunctionstmtContext); ok {
+ // First try to get text using token stream
+ if tokenStream := ctx.GetParser().GetTokenStream(); tokenStream != nil {
+ start := ctx.GetStart()
+ stop := ctx.GetStop()
+ if start != nil && stop != nil {
+ functionSQL = tokenStream.GetTextFromTokens(start, stop)
+ }
+ }
+
+ // Fallback to GetText() if token stream approach failed
+ if functionSQL == "" {
+ functionSQL = ctx.GetText()
+ }
+ } else {
+ return errors.Errorf("unsupported AST node type for function: %T", astNode)
+ }
+
+ if functionSQL == "" {
+ return errors.New("could not extract function SQL from AST node")
+ }
+
+ // Convert CREATE FUNCTION to CREATE OR REPLACE FUNCTION
+ functionSQL = convertToCreateOrReplace(functionSQL)
+
+ // Write the function SQL
+ _, _ = out.WriteString(functionSQL)
+ if !strings.HasSuffix(strings.TrimSpace(functionSQL), ";") {
+ _, _ = out.WriteString(";")
+ }
+ _, _ = out.WriteString("\n\n")
+
+ return nil
+}
+
// writeMaterializedView writes a CREATE MATERIALIZED VIEW statement
func writeMigrationMaterializedView(out *strings.Builder, schema string, view *storepb.MaterializedViewMetadata) error {
_, _ = out.WriteString(`CREATE MATERIALIZED VIEW "`)
diff --git a/backend/plugin/schema/pg/get_database_metadata.go b/backend/plugin/schema/pg/get_database_metadata.go
index 70940a18b5..6d8ee5de6f 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: e.extractFunctionSignature(ctx, funcName),
+ Signature: extractFunctionSignature(ctx, funcName),
}
if schemaMetadata.Functions == nil {
@@ -1601,7 +1601,7 @@ func (e *metadataExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
}
// extractFunctionSignature extracts the function signature with parameter types
-func (*metadataExtractor) extractFunctionSignature(ctx *parser.CreatefunctionstmtContext, funcName string) string {
+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 c6e724593d..44b1a19db0 100644
--- a/backend/plugin/schema/pg/get_sdl_diff.go
+++ b/backend/plugin/schema/pg/get_sdl_diff.go
@@ -150,15 +150,18 @@ func (l *sdlChunkExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
return
}
- // Join the parts to create the full identifier (schema.function_name or function_name)
+ // Join the parts to create the function name (schema.function_name or function_name)
funcName := strings.Join(funcNameParts, ".")
+ // Extract function signature for proper identification
+ funcSignature := extractFunctionSignature(ctx, funcName)
+
chunk := &schema.SDLChunk{
- Identifier: funcName,
+ Identifier: funcSignature, // Use signature instead of name
ASTNode: ctx,
}
- l.chunks.Functions[funcName] = chunk
+ l.chunks.Functions[funcSignature] = chunk
}
func (l *sdlChunkExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {
@@ -1271,24 +1274,15 @@ func processFunctionChanges(currentChunks, previousChunks *schema.SDLChunks, dif
currentText := currentChunk.GetText(currentChunks.Tokens)
previousText := previousChunk.GetText(previousChunks.Tokens)
if currentText != previousText {
- // Function was modified - use drop and recreate pattern (PostgreSQL standard)
+ // Function was modified - use CREATE OR REPLACE (AST-only mode)
schemaName, functionName := parseIdentifier(identifier)
diff.FunctionChanges = append(diff.FunctionChanges, &schema.FunctionDiff{
- Action: schema.MetadataDiffActionDrop,
+ Action: schema.MetadataDiffActionAlter,
SchemaName: schemaName,
FunctionName: functionName,
OldFunction: nil, // Will be populated when SDL drift detection is implemented
NewFunction: nil, // Will be populated when SDL drift detection is implemented
OldASTNode: previousChunk.ASTNode,
- NewASTNode: nil,
- })
- diff.FunctionChanges = append(diff.FunctionChanges, &schema.FunctionDiff{
- Action: schema.MetadataDiffActionCreate,
- SchemaName: schemaName,
- FunctionName: functionName,
- OldFunction: nil, // Will be populated when SDL drift detection is implemented
- NewFunction: nil, // Will be populated when SDL drift detection is implemented
- OldASTNode: nil,
NewASTNode: currentChunk.ASTNode,
})
}
diff --git a/backend/plugin/schema/pg/procedure_sdl_diff_test.go b/backend/plugin/schema/pg/procedure_sdl_diff_test.go
index 77e962eedf..81452c27fe 100644
--- a/backend/plugin/schema/pg/procedure_sdl_diff_test.go
+++ b/backend/plugin/schema/pg/procedure_sdl_diff_test.go
@@ -66,7 +66,7 @@ func TestProcedureSDLDiff(t *testing.T) {
expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop},
},
{
- name: "Modify procedure (drop and recreate)",
+ name: "Modify procedure (CREATE OR REPLACE)",
previousSDL: `
CREATE TABLE logs (
id SERIAL PRIMARY KEY,
@@ -97,8 +97,8 @@ func TestProcedureSDLDiff(t *testing.T) {
END;
$$;
`,
- expectedFunctionChanges: 2, // Drop + Create
- expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop, schema.MetadataDiffActionCreate},
+ expectedFunctionChanges: 1, // ALTER only
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionAlter},
},
{
name: "Mixed functions and procedures",
@@ -219,6 +219,11 @@ func TestProcedureSDLDiff(t *testing.T) {
"Function diff %d should have OldASTNode for DROP action", i)
assert.Nil(t, funcDiff.NewASTNode,
"Function diff %d should not have NewASTNode for DROP action", i)
+ case schema.MetadataDiffActionAlter:
+ assert.NotNil(t, funcDiff.OldASTNode,
+ "Function diff %d should have OldASTNode for ALTER action", i)
+ assert.NotNil(t, funcDiff.NewASTNode,
+ "Function diff %d should have NewASTNode for ALTER action", i)
default:
t.Errorf("Unexpected action %v for function diff %d", funcDiff.Action, i)
}