Skip to content

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

feat: support pg function and procedure for SDL diff (#17430)

rebelice55f2308be4ce
diff --git a/backend/plugin/parser/pg/pg.go b/backend/plugin/parser/pg/pg.go
index 5196848de3..7b9f0fab55 100644
--- a/backend/plugin/parser/pg/pg.go
+++ b/backend/plugin/parser/pg/pg.go
@@ -252,20 +252,55 @@ func NormalizePostgreSQLFuncName(ctx parser.IFunc_nameContext) []string {
var result []string
- // Handle simple function name
+ // Handle type_function_name (simple identifiers)
+ if ctx.Type_function_name() != nil {
+ result = append(result, normalizePostgreSQLTypeFunctionName(ctx.Type_function_name()))
+ }
+
+ // Handle qualified function name (colid + indirection)
if ctx.Colid() != nil {
result = append(result, NormalizePostgreSQLColid(ctx.Colid()))
+
+ // Handle indirection for qualified names
+ if ctx.Indirection() != nil {
+ parts := normalizePostgreSQLIndirection(ctx.Indirection())
+ result = append(result, parts...)
+ }
}
- // Handle qualified function name with indirection
- if ctx.Indirection() != nil {
- parts := normalizePostgreSQLIndirection(ctx.Indirection())
- result = append(result, parts...)
+ // Handle builtin function names
+ if ctx.Builtin_function_name() != nil {
+ result = append(result, ctx.Builtin_function_name().GetText())
+ }
+
+ // Handle special keywords LEFT/RIGHT
+ if len(result) == 0 && ctx.GetText() != "" {
+ // Fallback for special cases like LEFT, RIGHT keywords
+ result = append(result, strings.ToLower(ctx.GetText()))
}
return result
}
+// normalizePostgreSQLTypeFunctionName normalizes a type_function_name context.
+func normalizePostgreSQLTypeFunctionName(ctx parser.IType_function_nameContext) string {
+ if ctx == nil {
+ return ""
+ }
+
+ // type_function_name can be identifier, unreserved_keyword, plsql_unreserved_keyword, or type_func_name_keyword
+ text := ctx.GetText()
+
+ // Remove quotes if present and convert to lowercase for normalization
+ if len(text) >= 2 && text[0] == '"' && text[len(text)-1] == '"' {
+ // Quoted identifier - preserve case but remove quotes
+ return text[1 : len(text)-1]
+ }
+
+ // Unquoted identifier - convert to lowercase
+ return strings.ToLower(text)
+}
+
// NormalizePostgreSQLName normalizes the given name.
// nolint:revive
func NormalizePostgreSQLName(ctx parser.INameContext) string {
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.go
index ec59a78e9e..c0c95fb8f9 100644
--- a/backend/plugin/schema/differ.go
+++ b/backend/plugin/schema/differ.go
@@ -196,6 +196,8 @@ type FunctionDiff struct {
FunctionName string
OldFunction *storepb.FunctionMetadata
NewFunction *storepb.FunctionMetadata
+ OldASTNode any // AST node for old function
+ NewASTNode any // AST node for new function
// Detailed change information for advanced engines
SignatureChanged bool
@@ -212,6 +214,8 @@ type ProcedureDiff struct {
ProcedureName string
OldProcedure *storepb.ProcedureMetadata
NewProcedure *storepb.ProcedureMetadata
+ OldASTNode any // AST node for old procedure
+ NewASTNode any // AST node for new procedure
}
// SequenceDiff represents changes to a sequence.
diff --git a/backend/plugin/schema/pg/function_sdl_diff_test.go b/backend/plugin/schema/pg/function_sdl_diff_test.go
new file mode 100644
index 0000000000..f96880b9f3
--- /dev/null
+++ b/backend/plugin/schema/pg/function_sdl_diff_test.go
@@ -0,0 +1,313 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+)
+
+func TestFunctionSDLDiff(t *testing.T) {
+ tests := []struct {
+ name string
+ previousSDL string
+ currentSDL string
+ expectedFunctionChanges int
+ expectedActions []schema.MetadataDiffAction
+ }{
+ {
+ name: "Create new function",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE OR REPLACE FUNCTION get_user_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedFunctionChanges: 1,
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},
+ },
+ {
+ name: "Drop function",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE OR REPLACE FUNCTION get_user_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ expectedFunctionChanges: 1,
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop},
+ },
+ {
+ name: "Modify function (drop and recreate)",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE OR REPLACE FUNCTION get_user_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ active BOOLEAN DEFAULT true
+ );
+
+ CREATE OR REPLACE FUNCTION get_user_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users WHERE active = true);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedFunctionChanges: 2, // Drop + Create
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop, schema.MetadataDiffActionCreate},
+ },
+ {
+ name: "No changes to function",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE OR REPLACE FUNCTION get_user_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE OR REPLACE FUNCTION get_user_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedFunctionChanges: 0,
+ expectedActions: []schema.MetadataDiffAction{},
+ },
+ {
+ name: "Multiple functions with different changes",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE OR REPLACE FUNCTION get_all_users()
+ RETURNS SETOF users AS $$
+ BEGIN
+ RETURN QUERY SELECT * FROM users;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE OR REPLACE FUNCTION get_user_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL
+ );
+
+ CREATE OR REPLACE FUNCTION get_all_users()
+ RETURNS SETOF users AS $$
+ BEGIN
+ RETURN QUERY SELECT * FROM users;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE OR REPLACE FUNCTION get_admin_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users WHERE role = 'admin');
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedFunctionChanges: 2, // Drop get_user_count + Create get_admin_count
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate, schema.MetadataDiffActionDrop},
+ },
+ {
+ name: "Schema-qualified function names",
+ previousSDL: `
+ CREATE SCHEMA test_schema;
+ CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+ `,
+ currentSDL: `
+ CREATE SCHEMA test_schema;
+ CREATE TABLE test_schema.products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255)
+ );
+
+ CREATE OR REPLACE FUNCTION test_schema.get_product_count()
+ RETURNS INTEGER AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM test_schema.products);
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedFunctionChanges: 1,
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},
+ },
+ {
+ name: "Function with complex signature",
+ previousSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ amount DECIMAL(10,2),
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ amount DECIMAL(10,2),
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE OR REPLACE FUNCTION calculate_total(
+ p_start_date DATE,
+ p_end_date DATE,
+ p_discount_rate DECIMAL DEFAULT 0.0
+ )
+ RETURNS DECIMAL(10,2) AS $$
+ BEGIN
+ RETURN (
+ SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)
+ FROM orders
+ WHERE created_at::DATE BETWEEN p_start_date AND p_end_date
+ );
+ END;
+ $$ LANGUAGE plpgsql;
+ `,
+ expectedFunctionChanges: 1,
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ assert.Equal(t, tt.expectedFunctionChanges, len(diff.FunctionChanges),
+ "Expected %d function changes, got %d", tt.expectedFunctionChanges, len(diff.FunctionChanges))
+
+ // Check that the actions match expectations
+ var actualActions []schema.MetadataDiffAction
+ for _, funcDiff := range diff.FunctionChanges {
+ actualActions = append(actualActions, funcDiff.Action)
+ }
+
+ // Handle nil vs empty slice comparison
+ if len(tt.expectedActions) == 0 && len(actualActions) == 0 {
+ // Both are effectively empty - test passes
+ t.Log("Both expected and actual actions are empty")
+ } else {
+ assert.ElementsMatch(t, tt.expectedActions, actualActions,
+ "Expected actions %v, got %v", tt.expectedActions, actualActions)
+ }
+
+ // Verify AST nodes are properly set
+ for i, funcDiff := range diff.FunctionChanges {
+ switch funcDiff.Action {
+ case schema.MetadataDiffActionCreate:
+ assert.NotNil(t, funcDiff.NewASTNode,
+ "Function diff %d should have NewASTNode for CREATE action", i)
+ assert.Nil(t, funcDiff.OldASTNode,
+ "Function diff %d should not have OldASTNode for CREATE action", i)
+ case schema.MetadataDiffActionDrop:
+ assert.NotNil(t, funcDiff.OldASTNode,
+ "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)
+ default:
+ t.Errorf("Unexpected action %v for function diff %d", funcDiff.Action, i)
+ }
+ }
+ })
+ }
+}
+
+func TestFunctionIdentifierParsing(t *testing.T) {
+ tests := []struct {
+ name string
+ identifier string
+ expectedSchema string
+ expectedFunction string
+ }{
+ {
+ name: "Simple function name",
+ identifier: "my_function",
+ expectedSchema: "public",
+ expectedFunction: "my_function",
+ },
+ {
+ name: "Schema-qualified function name",
+ identifier: "test_schema.my_function",
+ expectedSchema: "test_schema",
+ expectedFunction: "my_function",
+ },
+ {
+ name: "Public schema explicit",
+ identifier: "public.user_summary_func",
+ expectedSchema: "public",
+ expectedFunction: "user_summary_func",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ schema, function := parseIdentifier(tt.identifier)
+ assert.Equal(t, tt.expectedSchema, schema)
+ assert.Equal(t, tt.expectedFunction, function)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.go
index 40fd5505a2..8df3f15116 100644
--- a/backend/plugin/schema/pg/get_sdl_diff.go
+++ b/backend/plugin/schema/pg/get_sdl_diff.go
@@ -55,6 +55,9 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previ
// Process view changes
processViewChanges(currentChunks, previousChunks, diff)
+ // Process function changes
+ processFunctionChanges(currentChunks, previousChunks, diff)
+
return diff, nil
}
@@ -138,12 +141,15 @@ func (l *sdlChunkExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
return
}
- // Extract function name directly from the text
- funcName := funcNameCtx.GetText()
- if funcName == "" {
+ // Extract function name using proper normalization
+ funcNameParts := pgparser.NormalizePostgreSQLFuncName(funcNameCtx)
+ if len(funcNameParts) == 0 {
return
}
+ // Join the parts to create the full identifier (schema.function_name or function_name)
+ funcName := strings.Join(funcNameParts, ".")
+
chunk := &schema.SDLChunk{
Identifier: funcName,
ASTNode: ctx,
@@ -1251,3 +1257,68 @@ func processViewChanges(currentChunks, previousChunks *schema.SDLChunks, diff *s
}
}
}
+
+// processFunctionChanges analyzes function changes between current and previous chunks
+// Following the text-first comparison pattern for performance optimization
+func processFunctionChanges(currentChunks, previousChunks *schema.SDLChunks, diff *schema.MetadataDiff) {
+ // Process current functions to find created and modified functions
+ for identifier, currentChunk := range currentChunks.Functions {
+ if previousChunk, exists := previousChunks.Functions[identifier]; exists {
+ // Function exists in both - check if modified by comparing text first
+ currentText := currentChunk.GetText(currentChunks.Tokens)
+ previousText := previousChunk.GetText(previousChunks.Tokens)
+ if currentText != previousText {
+ // Function was modified - use drop and recreate pattern (PostgreSQL standard)
+ schemaName, functionName := parseIdentifier(identifier)
+ diff.FunctionChanges = append(diff.FunctionChanges, &schema.FunctionDiff{
+ Action: schema.MetadataDiffActionDrop,
+ 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,
+ })
+ }
+ // If text is identical, skip - no changes detected
+ } else {
+ // New function
+ schemaName, functionName := parseIdentifier(identifier)
+ diff.FunctionChanges = append(diff.FunctionChanges, &schema.FunctionDiff{
+ Action: schema.MetadataDiffActionCreate,
+ SchemaName: schemaName,
+ FunctionName: functionName,
+ OldFunction: nil,
+ NewFunction: nil,
+ OldASTNode: nil,
+ NewASTNode: currentChunk.ASTNode,
+ })
+ }
+ }
+
+ // Process previous functions to find dropped ones
+ for identifier, previousChunk := range previousChunks.Functions {
+ if _, exists := currentChunks.Functions[identifier]; !exists {
+ // Function was dropped
+ schemaName, functionName := parseIdentifier(identifier)
+ diff.FunctionChanges = append(diff.FunctionChanges, &schema.FunctionDiff{
+ Action: schema.MetadataDiffActionDrop,
+ SchemaName: schemaName,
+ FunctionName: functionName,
+ OldFunction: nil, // Will be populated when SDL drift detection is implemented
+ NewFunction: nil,
+ OldASTNode: previousChunk.ASTNode,
+ NewASTNode: nil,
+ })
+ }
+ }
+}
diff --git a/backend/plugin/schema/pg/procedure_sdl_diff_test.go b/backend/plugin/schema/pg/procedure_sdl_diff_test.go
new file mode 100644
index 0000000000..77e962eedf
--- /dev/null
+++ b/backend/plugin/schema/pg/procedure_sdl_diff_test.go
@@ -0,0 +1,228 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+)
+
+func TestProcedureSDLDiff(t *testing.T) {
+ tests := []struct {
+ name string
+ previousSDL string
+ currentSDL string
+ expectedFunctionChanges int // Note: procedures are stored as functions in PostgreSQL
+ expectedActions []schema.MetadataDiffAction
+ }{
+ {
+ name: "Create new procedure",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message) VALUES (msg);
+ END;
+ $$;
+ `,
+ expectedFunctionChanges: 1,
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},
+ },
+ {
+ name: "Drop procedure",
+ previousSDL: `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message) VALUES (msg);
+ END;
+ $$;
+ `,
+ currentSDL: `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+ `,
+ expectedFunctionChanges: 1,
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop},
+ },
+ {
+ name: "Modify procedure (drop and recreate)",
+ previousSDL: `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message) VALUES (msg);
+ END;
+ $$;
+ `,
+ currentSDL: `
+ CREATE TABLE logs (
+ id SERIAL PRIMARY KEY,
+ message TEXT,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE PROCEDURE log_message(msg TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO logs (message, created_at) VALUES (msg, NOW());
+ END;
+ $$;
+ `,
+ expectedFunctionChanges: 2, // Drop + Create
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop, schema.MetadataDiffActionCreate},
+ },
+ {
+ name: "Mixed functions and procedures",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255),
+ email VARCHAR(255)
+ );
+
+ CREATE FUNCTION get_user_count() RETURNS INTEGER
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$;
+
+ CREATE PROCEDURE add_user(user_name TEXT, user_email TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO users (name, email) VALUES (user_name, user_email);
+ END;
+ $$;
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255),
+ email VARCHAR(255)
+ );
+
+ CREATE FUNCTION get_user_count() RETURNS INTEGER
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ RETURN (SELECT COUNT(*) FROM users);
+ END;
+ $$;
+
+ CREATE PROCEDURE update_user_email(user_id INTEGER, new_email TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ UPDATE users SET email = new_email WHERE id = user_id;
+ END;
+ $$;
+ `,
+ expectedFunctionChanges: 2, // Drop add_user + Create update_user_email
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate, schema.MetadataDiffActionDrop},
+ },
+ {
+ name: "Schema-qualified procedure",
+ previousSDL: `
+ CREATE SCHEMA admin;
+ CREATE TABLE admin.settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT
+ );
+ `,
+ currentSDL: `
+ CREATE SCHEMA admin;
+ CREATE TABLE admin.settings (
+ key VARCHAR(255) PRIMARY KEY,
+ value TEXT
+ );
+
+ CREATE PROCEDURE admin.update_setting(setting_key TEXT, setting_value TEXT)
+ LANGUAGE plpgsql
+ AS $$
+ BEGIN
+ INSERT INTO admin.settings (key, value) VALUES (setting_key, setting_value)
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
+ END;
+ $$;
+ `,
+ expectedFunctionChanges: 1,
+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Note: In PostgreSQL, procedures are stored as functions
+ assert.Equal(t, tt.expectedFunctionChanges, len(diff.FunctionChanges),
+ "Expected %d function changes (including procedures), got %d", tt.expectedFunctionChanges, len(diff.FunctionChanges))
+
+ // Check that the actions match expectations
+ var actualActions []schema.MetadataDiffAction
+ for _, funcDiff := range diff.FunctionChanges {
+ actualActions = append(actualActions, funcDiff.Action)
+ }
+
+ // Handle nil vs empty slice comparison
+ if len(tt.expectedActions) == 0 && len(actualActions) == 0 {
+ // Both are effectively empty - test passes
+ t.Log("Both expected and actual actions are empty")
+ } else {
+ assert.ElementsMatch(t, tt.expectedActions, actualActions,
+ "Expected actions %v, got %v", tt.expectedActions, actualActions)
+ }
+
+ // Verify AST nodes are properly set
+ for i, funcDiff := range diff.FunctionChanges {
+ switch funcDiff.Action {
+ case schema.MetadataDiffActionCreate:
+ assert.NotNil(t, funcDiff.NewASTNode,
+ "Function diff %d should have NewASTNode for CREATE action", i)
+ assert.Nil(t, funcDiff.OldASTNode,
+ "Function diff %d should not have OldASTNode for CREATE action", i)
+ case schema.MetadataDiffActionDrop:
+ assert.NotNil(t, funcDiff.OldASTNode,
+ "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)
+ default:
+ t.Errorf("Unexpected action %v for function diff %d", funcDiff.Action, i)
+ }
+ }
+ })
+ }
+}