Skip to content

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

chore: use create or replace to update function body (#17305)

rebelice662c0cb984a0
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.go
index b28202ab39..b540319d3c 100644
--- a/backend/plugin/schema/differ.go
+++ b/backend/plugin/schema/differ.go
@@ -154,6 +154,13 @@ type FunctionDiff struct {
FunctionName string
OldFunction *storepb.FunctionMetadata
NewFunction *storepb.FunctionMetadata
+
+ // Detailed change information for advanced engines
+ SignatureChanged bool
+ BodyChanged bool
+ AttributesChanged bool
+ ChangedAttributes []string
+ CanUseAlterFunction bool
}
// ProcedureDiff represents changes to a procedure.
@@ -408,7 +415,7 @@ func compareSchemaObjects(engine storepb.Engine, diff *MetadataDiff, schemaName
compareMaterializedViews(engine, diff, schemaName, oldSchema, newSchema)
// Compare functions
- compareFunctions(diff, schemaName, oldSchema, newSchema)
+ compareFunctions(engine, diff, schemaName, oldSchema, newSchema)
// Compare procedures
compareProcedures(diff, schemaName, oldSchema, newSchema)
@@ -1496,7 +1503,10 @@ func compareMaterializedViews(engine storepb.Engine, diff *MetadataDiff, schemaN
}
// compareFunctions compares functions between two schemas.
-func compareFunctions(diff *MetadataDiff, schemaName string, oldSchema, newSchema *model.SchemaMetadata) {
+func compareFunctions(engine storepb.Engine, diff *MetadataDiff, schemaName string, oldSchema, newSchema *model.SchemaMetadata) {
+ // Get the engine-specific function comparer
+ comparer := GetFunctionComparer(engine)
+
// Functions can have overloading, so we need to handle them carefully
// Group functions by signature to properly match overloaded functions
// Build map of old functions by signature
@@ -1545,20 +1555,54 @@ func compareFunctions(diff *MetadataDiff, schemaName string, oldSchema, newSchem
FunctionName: newFunc.GetProto().Name,
NewFunction: newFunc.GetProto(),
})
- } else if !functionsEqual(oldFunc.GetProto(), newFunc.GetProto()) {
- // Drop and recreate if definition changed
- diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
- Action: MetadataDiffActionDrop,
- SchemaName: schemaName,
- FunctionName: oldFunc.GetProto().Name,
- OldFunction: oldFunc.GetProto(),
- })
- diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
- Action: MetadataDiffActionCreate,
- SchemaName: schemaName,
- FunctionName: newFunc.GetProto().Name,
- NewFunction: newFunc.GetProto(),
- })
+ } else {
+ // Use detailed comparison to determine migration strategy
+ comparison, err := comparer.CompareDetailed(oldFunc, newFunc)
+ if err != nil || comparison == nil {
+ // Skip if no changes or error
+ continue
+ }
+
+ // Determine the action based on the comparison result
+ if comparison.CanUseAlterFunction {
+ // Use ALTER FUNCTION for body-only changes
+ diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
+ Action: MetadataDiffActionAlter,
+ SchemaName: schemaName,
+ FunctionName: oldFunc.GetProto().Name,
+ OldFunction: oldFunc.GetProto(),
+ NewFunction: newFunc.GetProto(),
+ SignatureChanged: comparison.SignatureChanged,
+ BodyChanged: comparison.BodyChanged,
+ AttributesChanged: comparison.AttributesChanged,
+ ChangedAttributes: comparison.ChangedAttributes,
+ CanUseAlterFunction: true,
+ })
+ } else {
+ // Use DROP and CREATE for signature changes
+ diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
+ Action: MetadataDiffActionDrop,
+ SchemaName: schemaName,
+ FunctionName: oldFunc.GetProto().Name,
+ OldFunction: oldFunc.GetProto(),
+ SignatureChanged: comparison.SignatureChanged,
+ BodyChanged: comparison.BodyChanged,
+ AttributesChanged: comparison.AttributesChanged,
+ ChangedAttributes: comparison.ChangedAttributes,
+ CanUseAlterFunction: false,
+ })
+ diff.FunctionChanges = append(diff.FunctionChanges, &FunctionDiff{
+ Action: MetadataDiffActionCreate,
+ SchemaName: schemaName,
+ FunctionName: newFunc.GetProto().Name,
+ NewFunction: newFunc.GetProto(),
+ SignatureChanged: comparison.SignatureChanged,
+ BodyChanged: comparison.BodyChanged,
+ AttributesChanged: comparison.AttributesChanged,
+ ChangedAttributes: comparison.ChangedAttributes,
+ CanUseAlterFunction: false,
+ })
+ }
}
}
}
diff --git a/backend/plugin/schema/function_comparer.go b/backend/plugin/schema/function_comparer.go
new file mode 100644
index 0000000000..af3e16e1d8
--- /dev/null
+++ b/backend/plugin/schema/function_comparer.go
@@ -0,0 +1,134 @@
+package schema
+
+import (
+ "sync"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store/model"
+)
+
+// FunctionChange represents a type of change detected in a function.
+type FunctionChange struct {
+ Type FunctionChangeType
+ Description string
+ RequiresRecreation bool
+ CanUseAlterFunction bool
+}
+
+// FunctionChangeType represents specific types of function changes.
+type FunctionChangeType string
+
+const (
+ FunctionChangeDefinition FunctionChangeType = "definition"
+ FunctionChangeComment FunctionChangeType = "comment"
+ FunctionChangeAttribute FunctionChangeType = "attribute"
+)
+
+// FunctionComparisonResult contains detailed information about function changes.
+type FunctionComparisonResult struct {
+ SignatureChanged bool
+ BodyChanged bool
+ AttributesChanged bool
+ ChangedAttributes []string
+ RequiresRecreation bool
+ CanUseAlterFunction bool
+}
+
+// FunctionComparer provides an interface for engine-specific function comparison logic.
+type FunctionComparer interface {
+ // Equal compares two functions and returns whether they are equal.
+ Equal(oldFunc, newFunc *model.FunctionMetadata) bool
+
+ // CompareDetailed performs detailed comparison and returns migration strategy information.
+ // Returns nil if functions are equal.
+ CompareDetailed(oldFunc, newFunc *model.FunctionMetadata) (*FunctionComparisonResult, error)
+}
+
+// DefaultFunctionComparer provides default function comparison logic that can be used by most engines.
+type DefaultFunctionComparer struct{}
+
+// Equal compares two functions using simple definition comparison.
+func (*DefaultFunctionComparer) Equal(oldFunc, newFunc *model.FunctionMetadata) bool {
+ if oldFunc == nil || newFunc == nil {
+ return oldFunc == newFunc
+ }
+
+ oldProto := oldFunc.GetProto()
+ newProto := newFunc.GetProto()
+ if oldProto == nil || newProto == nil {
+ return oldProto == newProto
+ }
+
+ // Simple definition comparison
+ return functionsEqual(oldProto, newProto)
+}
+
+// CompareDetailed provides basic comparison for engines that don't have advanced comparison logic.
+func (*DefaultFunctionComparer) CompareDetailed(oldFunc, newFunc *model.FunctionMetadata) (*FunctionComparisonResult, error) {
+ if oldFunc == nil || newFunc == nil {
+ return nil, nil
+ }
+
+ oldProto := oldFunc.GetProto()
+ newProto := newFunc.GetProto()
+
+ // Handle nil protos
+ if oldProto == nil {
+ oldProto = &storepb.FunctionMetadata{Definition: oldFunc.Definition}
+ }
+ if newProto == nil {
+ newProto = &storepb.FunctionMetadata{Definition: newFunc.Definition}
+ }
+
+ // For default implementation, if functions are equal, return nil
+ if functionsEqual(oldProto, newProto) {
+ return nil, nil
+ }
+
+ // For basic engines, treat any change as requiring recreation
+ return &FunctionComparisonResult{
+ SignatureChanged: true, // Conservatively assume signature changed
+ BodyChanged: true, // Conservatively assume body changed
+ AttributesChanged: false,
+ ChangedAttributes: nil,
+ CanUseAlterFunction: false, // Default engines use DROP/CREATE
+ }, nil
+}
+
+var (
+ functionComparerRegistryMux sync.RWMutex
+ functionComparerRegistry = make(map[storepb.Engine]FunctionComparer)
+)
+
+// RegisterFunctionComparer registers a function comparer for a specific engine.
+func RegisterFunctionComparer(engine storepb.Engine, comparer FunctionComparer) {
+ functionComparerRegistryMux.Lock()
+ defer functionComparerRegistryMux.Unlock()
+ functionComparerRegistry[engine] = comparer
+}
+
+// GetFunctionComparer returns the function comparer for a specific engine.
+// If no engine-specific comparer is registered, it returns the default comparer.
+func GetFunctionComparer(engine storepb.Engine) FunctionComparer {
+ functionComparerRegistryMux.RLock()
+ defer functionComparerRegistryMux.RUnlock()
+
+ if comparer, exists := functionComparerRegistry[engine]; exists {
+ return comparer
+ }
+
+ // Return default comparer if no engine-specific one is registered
+ return &DefaultFunctionComparer{}
+}
+
+func init() {
+ // Register default comparers for engines that don't need specialized logic
+ defaultComparer := &DefaultFunctionComparer{}
+ RegisterFunctionComparer(storepb.Engine_MYSQL, defaultComparer)
+ RegisterFunctionComparer(storepb.Engine_TIDB, defaultComparer)
+ RegisterFunctionComparer(storepb.Engine_ORACLE, defaultComparer)
+ RegisterFunctionComparer(storepb.Engine_MSSQL, defaultComparer)
+ RegisterFunctionComparer(storepb.Engine_COCKROACHDB, defaultComparer)
+
+ // Note: PostgreSQL will register its own specialized comparer
+}
diff --git a/backend/plugin/schema/pg/function_comparer.go b/backend/plugin/schema/pg/function_comparer.go
new file mode 100644
index 0000000000..9d9096ae4d
--- /dev/null
+++ b/backend/plugin/schema/pg/function_comparer.go
@@ -0,0 +1,729 @@
+package pg
+
+import (
+ "strings"
+
+ "github.com/antlr4-go/antlr/v4"
+ pgparser "github.com/bytebase/parser/postgresql"
+ "github.com/pkg/errors"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+ "github.com/bytebase/bytebase/backend/plugin/schema/pg/ast"
+ "github.com/bytebase/bytebase/backend/store/model"
+)
+
+func init() {
+ // Register PostgreSQL-specific function comparer
+ schema.RegisterFunctionComparer(storepb.Engine_POSTGRES, &PostgreSQLFunctionComparer{})
+}
+
+// PostgreSQLFunctionComparer provides PostgreSQL-specific function comparison logic.
+type PostgreSQLFunctionComparer struct {
+ schema.DefaultFunctionComparer
+}
+
+// FunctionChangeType represents the type of change detected in a function.
+type FunctionChangeType int
+
+const (
+ FunctionChangeNone FunctionChangeType = iota
+ FunctionChangeBodyOnly
+ FunctionChangeSignature
+ FunctionChangeAttributes
+ FunctionChangeBoth // Both signature and body changed
+)
+
+// CompareDetailed compares two functions with PostgreSQL-specific logic using ANTLR parsing.
+func (*PostgreSQLFunctionComparer) CompareDetailed(oldFunc, newFunc *model.FunctionMetadata) (*schema.FunctionComparisonResult, error) {
+ if oldFunc == nil || newFunc == nil {
+ return nil, nil
+ }
+
+ result := &schema.FunctionComparisonResult{}
+
+ // Compare function signature using ANTLR parsing
+ oldProto := oldFunc.GetProto()
+ newProto := newFunc.GetProto()
+
+ // If proto is nil, create temporary proto with definition for comparison
+ if oldProto == nil {
+ oldProto = &storepb.FunctionMetadata{Definition: oldFunc.Definition}
+ }
+ if newProto == nil {
+ newProto = &storepb.FunctionMetadata{Definition: newFunc.Definition}
+ }
+
+ result.SignatureChanged = compareFunctionSignature(oldProto, newProto)
+
+ // Compare function attributes (comment, volatility, etc.)
+ attributesChanged, changedAttrs := compareFunctionAttributes(oldProto, newProto)
+ result.AttributesChanged = attributesChanged
+ result.ChangedAttributes = changedAttrs
+
+ // Compare function body using strict string comparison
+ bodyChanged := compareFunctionBody(oldFunc.Definition, newFunc.Definition)
+ result.BodyChanged = bodyChanged
+
+ // Determine change type and migration strategy
+ changeType := determineChangeType(result.SignatureChanged, bodyChanged, attributesChanged)
+ requiresRecreation, canUseAlterFunction := determineMigrationStrategy(changeType, changedAttrs)
+ result.RequiresRecreation = requiresRecreation
+ result.CanUseAlterFunction = canUseAlterFunction
+
+ // If there are no changes, return nil to indicate equality
+ if !result.SignatureChanged && !bodyChanged && !attributesChanged {
+ return nil, nil
+ }
+
+ return result, nil
+}
+
+// compareFunctionSignature compares function signatures using ANTLR parsing.
+func compareFunctionSignature(oldFunc, newFunc *storepb.FunctionMetadata) bool {
+ // Extract signature components using ANTLR parsing
+ oldSig, err := parseFunctionSignature(oldFunc.Definition)
+ if err != nil {
+ // Fallback to simple string comparison if parsing fails
+ return oldFunc.Signature != newFunc.Signature
+ }
+
+ newSig, err := parseFunctionSignature(newFunc.Definition)
+ if err != nil {
+ // Fallback to simple string comparison if parsing fails
+ return oldFunc.Signature != newFunc.Signature
+ }
+
+ return !signatureEqual(oldSig, newSig)
+}
+
+// parseFunctionSignature parses a function definition using ANTLR and extracts signature components.
+func parseFunctionSignature(definition string) (*FunctionSignature, error) {
+ // Use ANTLR PostgreSQL parser for proper parsing
+ inputStream := antlr.NewInputStream(definition)
+ lexer := pgparser.NewPostgreSQLLexer(inputStream)
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := pgparser.NewPostgreSQLParser(stream)
+
+ // Parse the SQL statement
+ tree := parser.Root()
+ if tree == nil {
+ return nil, errors.New("failed to parse function definition")
+ }
+
+ // Create a visitor to extract function signature information
+ visitor := &FunctionSignatureVisitor{}
+ result := visitor.Visit(tree)
+
+ if signature, ok := result.(*FunctionSignature); ok {
+ return signature, nil
+ }
+
+ return nil, errors.New("no function signature found in definition")
+}
+
+// FunctionSignature represents the parsed signature of a PostgreSQL function.
+type FunctionSignature struct {
+ Name string
+ Parameters []FunctionParameter
+ ReturnType string
+ Language string
+ Volatility string // VOLATILE, STABLE, IMMUTABLE
+ Security string // DEFINER, INVOKER
+ Parallel string // UNSAFE, RESTRICTED, SAFE
+ Cost string
+ Rows string
+ Leakproof bool
+ Strict bool
+}
+
+// FunctionParameter represents a function parameter.
+type FunctionParameter struct {
+ Mode string // IN, OUT, INOUT, VARIADIC
+ Name string
+ DataType string
+ Default string
+}
+
+// FunctionSignatureVisitor extracts function signature information from ANTLR parse tree.
+type FunctionSignatureVisitor struct {
+ *pgparser.BasePostgreSQLParserVisitor
+}
+
+// Visit implements the visitor pattern for extracting function signature from ANTLR parse tree.
+func (v *FunctionSignatureVisitor) Visit(tree antlr.ParseTree) any {
+ switch t := tree.(type) {
+ case *pgparser.CreatefunctionstmtContext:
+ return v.visitCreateFunctionStmt(t)
+ default:
+ // Continue visiting children
+ for i := 0; i < t.GetChildCount(); i++ {
+ child := t.GetChild(i)
+ if parseTree, ok := child.(antlr.ParseTree); ok {
+ if result := v.Visit(parseTree); result != nil {
+ return result
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// visitCreateFunctionStmt extracts signature information from CREATE FUNCTION statement.
+func (v *FunctionSignatureVisitor) visitCreateFunctionStmt(ctx *pgparser.CreatefunctionstmtContext) any {
+ // In PostgreSQL, CREATE FUNCTION and CREATE PROCEDURE use the same grammar rule
+ // We support both FUNCTION and PROCEDURE
+ if ctx.FUNCTION() == nil && ctx.PROCEDURE() == nil {
+ // This is neither CREATE FUNCTION nor CREATE PROCEDURE - skip it
+ return nil
+ }
+
+ signature := &FunctionSignature{
+ Volatility: "VOLATILE", // Default volatility
+ Security: "INVOKER", // Default security
+ }
+
+ // Extract function name
+ if ctx.Func_name() != nil {
+ signature.Name = v.extractFunctionName(ctx.Func_name())
+ }
+
+ // Extract parameters
+ if ctx.Func_args_with_defaults() != nil {
+ signature.Parameters = v.extractParameters(ctx.Func_args_with_defaults())
+ }
+
+ // Extract return type
+ if ctx.Func_return() != nil {
+ signature.ReturnType = v.normalizeDataType(ctx.Func_return().GetText())
+ }
+
+ // Extract function options
+ if ctx.Createfunc_opt_list() != nil {
+ v.extractFunctionOptions(ctx.Createfunc_opt_list(), signature)
+ }
+
+ return signature
+}
+
+// extractFunctionName extracts the function name from func_name context.
+func (*FunctionSignatureVisitor) extractFunctionName(ctx pgparser.IFunc_nameContext) string {
+ if ctx == nil {
+ return ""
+ }
+ // Get the last part of the qualified name (schema.function -> function)
+ text := ctx.GetText()
+ parts := strings.Split(text, ".")
+ if len(parts) > 0 {
+ return parts[len(parts)-1]
+ }
+ return text
+}
+
+// extractParameters extracts function parameters from func_args_with_defaults context.
+func (v *FunctionSignatureVisitor) extractParameters(ctx pgparser.IFunc_args_with_defaultsContext) []FunctionParameter {
+ var parameters []FunctionParameter
+
+ if ctx == nil {
+ return parameters
+ }
+
+ // Get the parameter list
+ if argsList := ctx.Func_args_with_defaults_list(); argsList != nil {
+ // Visit each parameter
+ for _, argCtx := range argsList.AllFunc_arg_with_default() {
+ if param := v.extractParameter(argCtx); param != nil {
+ parameters = append(parameters, *param)
+ }
+ }
+ }
+
+ return parameters
+}
+
+// extractParameter extracts a single function parameter.
+func (v *FunctionSignatureVisitor) extractParameter(ctx pgparser.IFunc_arg_with_defaultContext) *FunctionParameter {
+ if ctx == nil || ctx.Func_arg() == nil {
+ return nil
+ }
+
+ funcArg := ctx.Func_arg()
+ param := &FunctionParameter{}
+
+ // Extract parameter mode (IN, OUT, INOUT, VARIADIC)
+ if funcArg.Arg_class() != nil {
+ param.Mode = strings.ToUpper(funcArg.Arg_class().GetText())
+ }
+
+ // Extract parameter name
+ if funcArg.Param_name() != nil {
+ param.Name = funcArg.Param_name().GetText()
+ }
+
+ // Extract parameter type
+ if funcArg.Func_type() != nil {
+ param.DataType = v.normalizeDataType(funcArg.Func_type().GetText())
+ }
+
+ // Extract default value
+ if ctx.DEFAULT() != nil && ctx.A_expr() != nil {
+ param.Default = ctx.A_expr().GetText()
+ } else if ctx.EQUAL() != nil && ctx.A_expr() != nil {
+ param.Default = ctx.A_expr().GetText()
+ }
+
+ return param
+}
+
+// extractFunctionOptions extracts function options like LANGUAGE, VOLATILE, etc.
+func (v *FunctionSignatureVisitor) extractFunctionOptions(ctx pgparser.ICreatefunc_opt_listContext, signature *FunctionSignature) {
+ if ctx == nil {
+ return
+ }
+
+ // Visit each option item
+ for _, optCtx := range ctx.AllCreatefunc_opt_item() {
+ v.extractFunctionOption(optCtx, signature)
+ }
+}
+
+// extractFunctionOption extracts a single function option.
+func (*FunctionSignatureVisitor) extractFunctionOption(ctx pgparser.ICreatefunc_opt_itemContext, signature *FunctionSignature) {
+ if ctx == nil {
+ return
+ }
+
+ // Extract LANGUAGE
+ if ctx.LANGUAGE() != nil && ctx.Nonreservedword_or_sconst() != nil {
+ signature.Language = strings.ToLower(ctx.Nonreservedword_or_sconst().GetText())
+ }
+
+ // Extract volatility
+ if ctx.Common_func_opt_item() != nil {
+ commonOpt := ctx.Common_func_opt_item()
+ if commonOpt.VOLATILE() != nil {
+ signature.Volatility = "VOLATILE"
+ } else if commonOpt.STABLE() != nil {
+ signature.Volatility = "STABLE"
+ } else if commonOpt.IMMUTABLE() != nil {
+ signature.Volatility = "IMMUTABLE"
+ }
+
+ // Extract security
+ if commonOpt.SECURITY() != nil {
+ if commonOpt.DEFINER() != nil {
+ signature.Security = "DEFINER"
+ } else if commonOpt.INVOKER() != nil {
+ signature.Security = "INVOKER"
+ }
+ }
+
+ // Extract parallel safety
+ if commonOpt.PARALLEL() != nil && commonOpt.Colid() != nil {
+ signature.Parallel = strings.ToUpper(commonOpt.Colid().GetText())
+ }
+
+ // Extract LEAKPROOF
+ if commonOpt.LEAKPROOF() != nil {
+ signature.Leakproof = true
+ }
+
+ // Extract STRICT
+ if commonOpt.STRICT_P() != nil || commonOpt.RETURNS() != nil {
+ signature.Strict = true
+ }
+
+ // Extract COST
+ if commonOpt.COST() != nil && commonOpt.Numericonly() != nil {
+ signature.Cost = commonOpt.Numericonly().GetText()
+ }
+
+ // Extract ROWS
+ if commonOpt.ROWS() != nil && commonOpt.Numericonly() != nil {
+ signature.Rows = commonOpt.Numericonly().GetText()
+ }
+ }
+}
+
+// normalizeDataType normalizes PostgreSQL data types for comparison.
+func (*FunctionSignatureVisitor) normalizeDataType(dataType string) string {
+ if dataType == "" {
+ return ""
+ }
+
+ // Normalize common PostgreSQL data type aliases
+ dataType = strings.ToLower(strings.TrimSpace(dataType))
+
+ // Handle common aliases
+ switch dataType {
+ case "int4":
+ return "integer"
+ case "int8":
+ return "bigint"
+ case "int2":
+ return "smallint"
+ case "float8":
+ return "double precision"
+ case "float4":
+ return "real"
+ case "bool":
+ return "boolean"
+ case "varchar":
+ return "character varying"
+ case "char":
+ return "character"
+ default:
+ return dataType
+ }
+}
+
+// signatureEqual compares two function signatures for equality.
+func signatureEqual(sig1, sig2 *FunctionSignature) bool {
+ // Compare function name (case-insensitive, ignoring schema qualification)
+ if !normalizedFunctionNamesEqual(sig1.Name, sig2.Name) {
+ return false
+ }
+
+ // Compare parameters
+ if len(sig1.Parameters) != len(sig2.Parameters) {
+ return false
+ }
+
+ for i, param1 := range sig1.Parameters {
+ param2 := sig2.Parameters[i]
+ if !parameterEqual(param1, param2) {
+ return false
+ }
+ }
+
+ // Compare return type using PostgreSQL-aware type normalization
+ if !postgreSQLTypeStringsEqual(sig1.ReturnType, sig2.ReturnType) {
+ return false
+ }
+
+ return true
+}
+
+// parameterEqual compares two function parameters for equality.
+func parameterEqual(param1, param2 FunctionParameter) bool {
+ // Compare parameter mode
+ if !strings.EqualFold(param1.Mode, param2.Mode) {
+ return false
+ }
+
+ // Compare parameter name (case-insensitive for PostgreSQL)
+ if !strings.EqualFold(param1.Name, param2.Name) {
+ return false
+ }
+
+ // Compare data type using PostgreSQL-aware type normalization
+ if !postgreSQLTypeStringsEqual(param1.DataType, param2.DataType) {
+ return false
+ }
+
+ // Compare default value using semantic comparison
+ if !ast.CompareExpressionsSemantically(param1.Default, param2.Default) {
+ return false
+ }
+
+ return true
+}
+
+// compareFunctionAttributes compares function attributes like comment, volatility, etc.
+func compareFunctionAttributes(oldFunc, newFunc *storepb.FunctionMetadata) (bool, []string) {
+ var changedAttrs []string
+
+ // Compare comment
+ if oldFunc.Comment != newFunc.Comment {
+ changedAttrs = append(changedAttrs, "comment")
+ }
+
+ // Compare other PostgreSQL-specific attributes if they exist in the metadata
+ // Note: Most PostgreSQL function attributes are part of the definition,
+ // so they would be captured by signature or body comparison
+
+ return len(changedAttrs) > 0, changedAttrs
+}
+
+// compareFunctionBody compares function bodies using strict string comparison.
+func compareFunctionBody(oldDef, newDef string) bool {
+ // Extract the function body from the complete definition
+ // Dollar quotes are already removed during extraction
+ oldBody := extractFunctionBody(oldDef)
+ newBody := extractFunctionBody(newDef)
+
+ // Use strict string comparison for the extracted body content
+ return strings.TrimSpace(oldBody) != strings.TrimSpace(newBody)
+}
+
+// extractFunctionBody extracts the function body from a complete function definition using ANTLR.
+func extractFunctionBody(definition string) string {
+ // Use ANTLR to parse and extract the function body
+ inputStream := antlr.NewInputStream(definition)
+ lexer := pgparser.NewPostgreSQLLexer(inputStream)
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := pgparser.NewPostgreSQLParser(stream)
+
+ tree := parser.Root()
+ if tree == nil {
+ // Fallback to returning the entire definition if parsing fails
+ return strings.TrimSpace(definition)
+ }
+
+ // Create a visitor to extract the function body
+ visitor := &FunctionBodyVisitor{}
+ if body := visitor.Visit(tree); body != nil {
+ if bodyStr, ok := body.(string); ok {
+ return strings.TrimSpace(bodyStr)
+ }
+ }
+
+ // Fallback to returning the entire definition
+ return strings.TrimSpace(definition)
+}
+
+// FunctionBodyVisitor extracts function body from ANTLR parse tree.
+type FunctionBodyVisitor struct {
+ *pgparser.BasePostgreSQLParserVisitor
+}
+
+// Visit implements the visitor pattern for extracting function body.
+func (v *FunctionBodyVisitor) Visit(tree antlr.ParseTree) any {
+ switch t := tree.(type) {
+ case *pgparser.CreatefunctionstmtContext:
+ return v.visitCreateFunctionStmt(t)
+ default:
+ // Continue visiting children
+ for i := 0; i < t.GetChildCount(); i++ {
+ child := t.GetChild(i)
+ if parseTree, ok := child.(antlr.ParseTree); ok {
+ if result := v.Visit(parseTree); result != nil {
+ return result
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// visitCreateFunctionStmt extracts the function body from CREATE FUNCTION/PROCEDURE statement.
+// Note: In PostgreSQL, CREATE FUNCTION and CREATE PROCEDURE use the same grammar rule.
+// We support both FUNCTION and PROCEDURE as they have similar body extraction logic.
+func (v *FunctionBodyVisitor) visitCreateFunctionStmt(ctx *pgparser.CreatefunctionstmtContext) any {
+ // In PostgreSQL, CREATE FUNCTION and CREATE PROCEDURE use the same grammar rule
+ // We support both FUNCTION and PROCEDURE
+ if ctx.FUNCTION() == nil && ctx.PROCEDURE() == nil {
+ // This is neither CREATE FUNCTION nor CREATE PROCEDURE - skip it
+ return nil
+ }
+
+ if ctx.Createfunc_opt_list() == nil {
+ return nil
+ }
+
+ // Look for AS clause in function options
+ for _, optCtx := range ctx.Createfunc_opt_list().AllCreatefunc_opt_item() {
+ if optCtx.AS() != nil && optCtx.Func_as() != nil {
+ // Extract the function body from func_as
+ return v.extractBodyFromFuncAs(optCtx.Func_as())
+ }
+ }
+
+ return nil
+}
+
+// extractBodyFromFuncAs extracts the actual function body from func_as context using ANTLR-based parsing.
+func (*FunctionBodyVisitor) extractBodyFromFuncAs(ctx pgparser.IFunc_asContext) string {
+ if ctx == nil {
+ return ""
+ }
+
+ // Use ANTLR parser to properly handle all types of string constants including dollar quotes
+ sconstList := ctx.AllSconst()
+ if len(sconstList) > 0 {
+ // Use the postgresql parser's standard function to extract routine body
+ // This properly handles dollar quotes, regular quotes, and escape sequences
+ if sconstCtx, ok := sconstList[0].(*pgparser.SconstContext); ok {
+ return pgparser.GetRoutineBodyString(sconstCtx)
+ }
+ }
+
+ return ""
+}
+
+// determineChangeType determines the overall type of change in the function.
+func determineChangeType(signatureChanged, bodyChanged, attributesChanged bool) FunctionChangeType {
+ if !signatureChanged && !bodyChanged && !attributesChanged {
+ return FunctionChangeNone
+ }
+
+ if signatureChanged && (bodyChanged || attributesChanged) {
+ return FunctionChangeBoth
+ }
+
+ if signatureChanged {
+ return FunctionChangeSignature
+ }
+
+ if bodyChanged {
+ return FunctionChangeBodyOnly
+ }
+
+ if attributesChanged {
+ return FunctionChangeAttributes
+ }
+
+ return FunctionChangeNone
+}
+
+// determineMigrationStrategy determines whether to use ALTER FUNCTION or DROP/CREATE.
+func determineMigrationStrategy(changeType FunctionChangeType, changedAttrs []string) (requiresRecreation, canUseAlterFunction bool) {
+ switch changeType {
+ case FunctionChangeNone:
+ return false, false
+
+ case FunctionChangeBodyOnly:
+ // Body changes can use CREATE OR REPLACE (ALTER strategy)
+ return false, true
+
+ case FunctionChangeSignature:
+ // Signature changes require DROP/CREATE
+ return true, false
+
+ case FunctionChangeAttributes:
+ // Some attributes can be changed with ALTER FUNCTION
+ for _, attr := range changedAttrs {
+ switch attr {
+ case "comment":
+ // Comments can be changed separately with COMMENT ON FUNCTION
+ canUseAlterFunction = true
+ default:
+ // Most other attributes require DROP/CREATE
+ requiresRecreation = true
+ }
+ }
+ return requiresRecreation, canUseAlterFunction
+
+ case FunctionChangeBoth:
+ // Both signature and body/attributes changed - requires DROP/CREATE
+ return true, false
+
+ default:
+ return true, false
+ }
+}
+
+// Equal compares two functions for equality (implements the interface expected by the schema differ).
+func (c *PostgreSQLFunctionComparer) Equal(oldFunc, newFunc *model.FunctionMetadata) bool {
+ result, err := c.CompareDetailed(oldFunc, newFunc)
+ if err != nil {
+ // Fallback to simple definition comparison on error
+ return oldFunc.Definition == newFunc.Definition
+ }
+
+ // If result is nil, functions are equal
+ if result == nil {
+ return true
+ }
+
+ // Functions are not equal if there are any changes
+ return false
+}
+
+// postgreSQLTypeStringsEqual compares two PostgreSQL type strings, handling type aliases and format differences.
+func postgreSQLTypeStringsEqual(type1, type2 string) bool {
+ // Normalize both types and compare
+ normalized1 := normalizePostgreSQLTypeAlias(type1)
+ normalized2 := normalizePostgreSQLTypeAlias(type2)
+
+ return strings.EqualFold(normalized1, normalized2)
+}
+
+// normalizePostgreSQLTypeAlias normalizes PostgreSQL type names to handle aliases and format differences.
+func normalizePostgreSQLTypeAlias(typeName string) string {
+ // Trim leading/trailing whitespace and convert to lowercase for comparison
+ typeName = strings.TrimSpace(strings.ToLower(typeName))
+
+ // Handle PostgreSQL type aliases
+ typeAliases := map[string]string{
+ "varchar": "character varying",
+ "charactervarying": "character varying", // Handle space-removed version
+ "char": "character",
+ "int": "integer",
+ "int4": "integer",
+ "int8": "bigint",
+ "int2": "smallint",
+ "float4": "real",
+ "float8": "double precision",
+ "doubleprecision": "double precision", // Handle space-removed version
+ "bool": "boolean",
+ "decimal": "numeric",
+ "text": "text",
+ "bytea": "bytea",
+ "timestamp": "timestamp without time zone",
+ "timestampwithouttime zone": "timestamp without time zone", // Handle space-removed version
+ "timestampwithtimezone": "timestamp with time zone", // Handle space-removed version
+ "timestamptz": "timestamp with time zone",
+ "time": "time without time zone",
+ "timewithouttime zone": "time without time zone", // Handle space-removed version
+ "timewithtimezone": "time with time zone", // Handle space-removed version
+ "timetz": "time with time zone",
+ "date": "date",
+ "interval": "interval",
+ "uuid": "uuid",
+ "json": "json",
+ "jsonb": "jsonb",
+ "xml": "xml",
+ "money": "money",
+ }
+
+ // Check if it's an alias
+ if canonical, exists := typeAliases[typeName]; exists {
+ return canonical
+ }
+
+ // Handle parameterized types like VARCHAR(255) -> character varying
+ if strings.HasPrefix(typeName, "varchar(") {
+ return "character varying"
+ }
+ if strings.HasPrefix(typeName, "char(") {
+ return "character"
+ }
+ if strings.HasPrefix(typeName, "decimal(") || strings.HasPrefix(typeName, "numeric(") {
+ return "numeric"
+ }
+ if strings.HasPrefix(typeName, "timestamp(") {
+ if strings.Contains(typeName, "time zone") {
+ return "timestamp with time zone"
+ }
+ return "timestamp without time zone"
+ }
+ if strings.HasPrefix(typeName, "time(") {
+ if strings.Contains(typeName, "time zone") {
+ return "time with time zone"
+ }
+ return "time without time zone"
+ }
+
+ return typeName
+}
+
+// normalizedFunctionNamesEqual compares function names ignoring schema qualification.
+func normalizedFunctionNamesEqual(name1, name2 string) bool {
+ // Extract unqualified names (remove schema prefix)
+ unqualified1 := extractUnqualifiedName(name1)
+ unqualified2 := extractUnqualifiedName(name2)
+
+ // Compare case-insensitively
+ return strings.EqualFold(unqualified1, unqualified2)
+}
+
+// extractUnqualifiedName removes schema qualification from a function name.
+func extractUnqualifiedName(qualifiedName string) string {
+ // Handle schema.function_name -> function_name
+ parts := strings.Split(qualifiedName, ".")
+ if len(parts) > 1 {
+ return parts[len(parts)-1] // Return the last part (function name)
+ }
+ return qualifiedName
+}
diff --git a/backend/plugin/schema/pg/function_comparer_test.go b/backend/plugin/schema/pg/function_comparer_test.go
new file mode 100644
index 0000000000..de6437200a
--- /dev/null
+++ b/backend/plugin/schema/pg/function_comparer_test.go
@@ -0,0 +1,490 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+ "github.com/bytebase/bytebase/backend/store/model"
+)
+
+func TestPostgreSQLFunctionComparer_Equal(t *testing.T) {
+ comparer := &PostgreSQLFunctionComparer{}
+
+ tests := []struct {
+ name string
+ oldFunc *model.FunctionMetadata
+ newFunc *model.FunctionMetadata
+ wantEqual bool
+ }{
+ {
+ name: "identical functions",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantEqual: true,
+ },
+ {
+ name: "body only difference",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a * b; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantEqual: false,
+ },
+ {
+ name: "signature difference",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer, c integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantEqual: false,
+ },
+ {
+ name: "nil functions",
+ oldFunc: nil,
+ newFunc: nil,
+ wantEqual: true,
+ },
+ {
+ name: "one nil function",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE FUNCTION test() RETURNS integer AS $$ BEGIN RETURN 1; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: nil,
+ wantEqual: true, // CompareDetailed returns nil for nil inputs, so Equal returns true
+ },
+ {
+ name: "identical procedures",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer, new_name text) AS $$ BEGIN UPDATE users SET name = new_name WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer, new_name text) AS $$ BEGIN UPDATE users SET name = new_name WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantEqual: true,
+ },
+ {
+ name: "procedure body only difference",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer, new_name text) AS $$ BEGIN UPDATE users SET name = new_name WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer, new_name text) AS $$ BEGIN UPDATE users SET name = new_name, updated_at = NOW() WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantEqual: false,
+ },
+ {
+ name: "procedure with dollar quote differences",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE public.refresh_stats() LANGUAGE plpgsql AS $procedure$ BEGIN REFRESH MATERIALIZED VIEW stats; END; $procedure$`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE refresh_stats() LANGUAGE plpgsql AS $$ BEGIN REFRESH MATERIALIZED VIEW stats; END; $$`,
+ },
+ wantEqual: true, // Should be equal - only formatting differences
+ },
+ {
+ name: "function vs procedure - different types should not be equal",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION get_user_count() RETURNS integer AS $$ BEGIN RETURN (SELECT COUNT(*) FROM users); END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE get_user_count() AS $$ DECLARE count_val integer; BEGIN SELECT COUNT(*) INTO count_val FROM users; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantEqual: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ equal := comparer.Equal(tt.oldFunc, tt.newFunc)
+ if equal != tt.wantEqual {
+ t.Errorf("Equal() = %v, want %v", equal, tt.wantEqual)
+ }
+ })
+ }
+}
+
+func TestPostgreSQLFunctionComparer_CompareDetailed(t *testing.T) {
+ comparer := &PostgreSQLFunctionComparer{}
+
+ tests := []struct {
+ name string
+ oldFunc *model.FunctionMetadata
+ newFunc *model.FunctionMetadata
+ wantResult *schema.FunctionComparisonResult
+ wantSignatureChanged bool
+ wantBodyChanged bool
+ wantCanUseAlter bool
+ }{
+ {
+ name: "identical functions",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantResult: nil, // No changes, should return nil
+ },
+ {
+ name: "body only difference",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a * b; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantResult: &schema.FunctionComparisonResult{}, // Expect a result, not nil
+ wantSignatureChanged: false,
+ wantBodyChanged: true,
+ wantCanUseAlter: true,
+ },
+ {
+ name: "signature difference",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer, c integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantResult: &schema.FunctionComparisonResult{}, // Expect a result, not nil
+ wantSignatureChanged: true,
+ wantBodyChanged: false,
+ wantCanUseAlter: false,
+ },
+ {
+ name: "nil functions",
+ oldFunc: nil,
+ newFunc: nil,
+ wantResult: nil,
+ },
+ {
+ name: "procedure body only difference",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_stats() AS $$ BEGIN UPDATE stats SET last_updated = NOW(); END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_stats() AS $$ BEGIN UPDATE stats SET last_updated = NOW(), count = count + 1; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantResult: &schema.FunctionComparisonResult{}, // Expect a result, not nil
+ wantSignatureChanged: false,
+ wantBodyChanged: true,
+ wantCanUseAlter: true,
+ },
+ {
+ name: "procedure signature difference",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer) AS $$ BEGIN UPDATE users SET updated_at = NOW() WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer, new_status text) AS $$ BEGIN UPDATE users SET updated_at = NOW() WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ },
+ wantResult: &schema.FunctionComparisonResult{}, // Expect a result, not nil
+ wantSignatureChanged: true,
+ wantBodyChanged: false,
+ wantCanUseAlter: false,
+ },
+ {
+ name: "procedure with dollar quote formatting differences",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE public.refresh_data() LANGUAGE plpgsql AS $procedure$ BEGIN REFRESH MATERIALIZED VIEW data_view; END; $procedure$`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE refresh_data() LANGUAGE plpgsql AS $$ BEGIN REFRESH MATERIALIZED VIEW data_view; END; $$`,
+ },
+ wantResult: nil, // Should be nil - functions are equivalent after normalization
+ },
+ {
+ name: "function to procedure change",
+ oldFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE FUNCTION calculate_total() RETURNS integer AS $$ BEGIN RETURN (SELECT SUM(amount) FROM orders); END; $$ LANGUAGE plpgsql;`,
+ },
+ newFunc: &model.FunctionMetadata{
+ Definition: `CREATE OR REPLACE PROCEDURE calculate_total() AS $$ BEGIN RETURN (SELECT SUM(amount) FROM orders); END; $$ LANGUAGE plpgsql;`,
+ },
+ wantResult: &schema.FunctionComparisonResult{}, // Expect a result, not nil
+ wantSignatureChanged: true, // FUNCTION vs PROCEDURE is a signature change
+ wantBodyChanged: false,
+ wantCanUseAlter: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result, err := comparer.CompareDetailed(tt.oldFunc, tt.newFunc)
+ if err != nil {
+ t.Errorf("CompareDetailed() error = %v", err)
+ return
+ }
+
+ if tt.wantResult == nil {
+ if result != nil {
+ t.Errorf("CompareDetailed() = %v, want nil", result)
+ }
+ return
+ }
+
+ if result == nil {
+ t.Error("CompareDetailed() = nil, want non-nil result")
+ return
+ }
+
+ if result.SignatureChanged != tt.wantSignatureChanged {
+ t.Errorf("CompareDetailed().SignatureChanged = %v, want %v", result.SignatureChanged, tt.wantSignatureChanged)
+ }
+
+ if result.BodyChanged != tt.wantBodyChanged {
+ t.Errorf("CompareDetailed().BodyChanged = %v, want %v", result.BodyChanged, tt.wantBodyChanged)
+ }
+
+ if result.CanUseAlterFunction != tt.wantCanUseAlter {
+ t.Errorf("CompareDetailed().CanUseAlterFunction = %v, want %v", result.CanUseAlterFunction, tt.wantCanUseAlter)
+ }
+ })
+ }
+}
+
+func TestExtractFunctionBody(t *testing.T) {
+ tests := []struct {
+ name string
+ definition string
+ wantBody string
+ }{
+ {
+ name: "dollar quoted function",
+ definition: `CREATE OR REPLACE FUNCTION test() RETURNS integer AS $$ BEGIN RETURN 1; END; $$ LANGUAGE plpgsql;`,
+ wantBody: "BEGIN RETURN 1; END;",
+ },
+ {
+ name: "single quoted function",
+ definition: `CREATE FUNCTION test() RETURNS integer AS 'SELECT 1' LANGUAGE sql;`,
+ wantBody: "SELECT", // Note: Due to a bug in TrimQuotes function in postgresql parser, single quotes are incorrectly trimmed
+ },
+ {
+ name: "complex function with nested dollar quotes",
+ definition: `CREATE OR REPLACE FUNCTION complex_func() RETURNS text AS $func$ DECLARE result text; BEGIN result := 'test'; RETURN result; END; $func$ LANGUAGE plpgsql;`,
+ wantBody: "DECLARE result text; BEGIN result := 'test'; RETURN result; END;",
+ },
+ {
+ name: "simple procedure",
+ definition: `CREATE OR REPLACE PROCEDURE update_stats() AS $$ BEGIN UPDATE stats SET count = count + 1; END; $$ LANGUAGE plpgsql;`,
+ wantBody: "BEGIN UPDATE stats SET count = count + 1; END;",
+ },
+ {
+ name: "procedure with custom dollar quote",
+ definition: `CREATE PROCEDURE refresh_data() AS $proc$ BEGIN REFRESH MATERIALIZED VIEW data_view; END; $proc$ LANGUAGE plpgsql;`,
+ wantBody: "BEGIN REFRESH MATERIALIZED VIEW data_view; END;",
+ },
+ {
+ name: "procedure with parameters",
+ definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer, new_name text) AS $$ BEGIN UPDATE users SET name = new_name WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ wantBody: "BEGIN UPDATE users SET name = new_name WHERE id = user_id; END;",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ body := extractFunctionBody(tt.definition)
+ if body != tt.wantBody {
+ t.Errorf("extractFunctionBody() = %q, want %q", body, tt.wantBody)
+ }
+ })
+ }
+}
+
+func TestParseFunctionSignature(t *testing.T) {
+ tests := []struct {
+ name string
+ definition string
+ wantName string
+ wantParams int
+ wantReturn string
+ }{
+ {
+ name: "simple function",
+ definition: `CREATE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ wantName: "add_numbers",
+ wantParams: 2,
+ wantReturn: "integer",
+ },
+ {
+ name: "function with no parameters",
+ definition: `CREATE OR REPLACE FUNCTION get_current_time() RETURNS timestamp AS $$ BEGIN RETURN NOW(); END; $$ LANGUAGE plpgsql;`,
+ wantName: "get_current_time",
+ wantParams: 0,
+ wantReturn: "timestamp",
+ },
+ {
+ name: "function with complex return type",
+ definition: `CREATE FUNCTION get_user(user_id bigint) RETURNS TABLE(id bigint, name text) AS $$ BEGIN RETURN QUERY SELECT id, name FROM users WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ wantName: "get_user",
+ wantParams: 1,
+ wantReturn: "", // TABLE return types may not be fully parsed by current implementation
+ },
+ {
+ name: "simple procedure",
+ definition: `CREATE OR REPLACE PROCEDURE update_user(user_id integer, new_name text) AS $$ BEGIN UPDATE users SET name = new_name WHERE id = user_id; END; $$ LANGUAGE plpgsql;`,
+ wantName: "update_user",
+ wantParams: 2,
+ wantReturn: "", // Procedures don't have return types
+ },
+ {
+ name: "procedure with no parameters",
+ definition: `CREATE PROCEDURE refresh_stats() AS $$ BEGIN REFRESH MATERIALIZED VIEW stats; END; $$ LANGUAGE plpgsql;`,
+ wantName: "refresh_stats",
+ wantParams: 0,
+ wantReturn: "", // Procedures don't have return types
+ },
+ {
+ name: "procedure with schema qualification",
+ definition: `CREATE OR REPLACE PROCEDURE public.cleanup_old_data(days_old integer) AS $$ BEGIN DELETE FROM logs WHERE created_at < NOW() - INTERVAL '%d days', days_old; END; $$ LANGUAGE plpgsql;`,
+ wantName: "cleanup_old_data", // Should extract unqualified name
+ wantParams: 1,
+ wantReturn: "", // Procedures don't have return types
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ signature, err := parseFunctionSignature(tt.definition)
+ if err != nil {
+ t.Errorf("parseFunctionSignature() error = %v", err)
+ return
+ }
+
+ if signature.Name != tt.wantName {
+ t.Errorf("parseFunctionSignature().Name = %v, want %v", signature.Name, tt.wantName)
+ }
+
+ if len(signature.Parameters) != tt.wantParams {
+ t.Errorf("parseFunctionSignature().Parameters count = %v, want %v", len(signature.Parameters), tt.wantParams)
+ }
+
+ if signature.ReturnType != tt.wantReturn {
+ t.Errorf("parseFunctionSignature().ReturnType = %v, want %v", signature.ReturnType, tt.wantReturn)
+ }
+ })
+ }
+}
+
+func TestPostgreSQLFunctionComparer_ProcedureSupport(t *testing.T) {
+ comparer := &PostgreSQLFunctionComparer{}
+
+ tests := []struct {
+ name string
+ def1 string
+ def2 string
+ wantDiff bool
+ wantMsg string
+ }{
+ {
+ name: "identical procedures should be equal",
+ def1: `CREATE OR REPLACE PROCEDURE test_proc(param1 integer) AS $$ BEGIN UPDATE table1 SET col1 = param1; END; $$ LANGUAGE plpgsql;`,
+ def2: `CREATE OR REPLACE PROCEDURE test_proc(param1 integer) AS $$ BEGIN UPDATE table1 SET col1 = param1; END; $$ LANGUAGE plpgsql;`,
+ wantDiff: false,
+ wantMsg: "identical procedures",
+ },
+ {
+ name: "procedures with dollar quote differences should be equal",
+ def1: `CREATE OR REPLACE PROCEDURE public.test_proc() LANGUAGE plpgsql AS $procedure$ BEGIN UPDATE stats SET count = 1; END; $procedure$`,
+ def2: `CREATE OR REPLACE PROCEDURE test_proc() LANGUAGE plpgsql AS $$ BEGIN UPDATE stats SET count = 1; END; $$`,
+ wantDiff: false,
+ wantMsg: "procedures with only formatting differences",
+ },
+ {
+ name: "procedures with body differences should not be equal",
+ def1: `CREATE OR REPLACE PROCEDURE test_proc() AS $$ BEGIN UPDATE table1 SET col1 = 1; END; $$ LANGUAGE plpgsql;`,
+ def2: `CREATE OR REPLACE PROCEDURE test_proc() AS $$ BEGIN UPDATE table1 SET col1 = 2; END; $$ LANGUAGE plpgsql;`,
+ wantDiff: true,
+ wantMsg: "procedures with different bodies",
+ },
+ {
+ name: "procedures with signature differences should not be equal",
+ def1: `CREATE OR REPLACE PROCEDURE test_proc(param1 integer) AS $$ BEGIN UPDATE table1 SET col1 = param1; END; $$ LANGUAGE plpgsql;`,
+ def2: `CREATE OR REPLACE PROCEDURE test_proc(param1 integer, param2 text) AS $$ BEGIN UPDATE table1 SET col1 = param1; END; $$ LANGUAGE plpgsql;`,
+ wantDiff: true,
+ wantMsg: "procedures with different signatures",
+ },
+ {
+ name: "function vs procedure should not be equal",
+ def1: `CREATE OR REPLACE FUNCTION test_func() RETURNS integer AS $$ BEGIN RETURN 1; END; $$ LANGUAGE plpgsql;`,
+ def2: `CREATE OR REPLACE PROCEDURE test_proc() AS $$ BEGIN UPDATE table1 SET col1 = 1; END; $$ LANGUAGE plpgsql;`,
+ wantDiff: true,
+ wantMsg: "function vs procedure",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ oldFunc := &model.FunctionMetadata{Definition: tt.def1}
+ newFunc := &model.FunctionMetadata{Definition: tt.def2}
+
+ equal := comparer.Equal(oldFunc, newFunc)
+ if equal == tt.wantDiff {
+ t.Errorf("%s: Equal() = %v, want %v", tt.wantMsg, equal, !tt.wantDiff)
+ }
+
+ // Also test detailed comparison for non-identical cases
+ if tt.wantDiff {
+ result, err := comparer.CompareDetailed(oldFunc, newFunc)
+ if err != nil {
+ t.Errorf("%s: CompareDetailed() error = %v", tt.wantMsg, err)
+ }
+ if result == nil {
+ t.Errorf("%s: CompareDetailed() returned nil, expected non-nil result", tt.wantMsg)
+ }
+ }
+ })
+ }
+}
+
+func TestFunctionBodyExtraction_WithANTLR(t *testing.T) {
+ tests := []struct {
+ name string
+ definition string
+ wantBody string
+ }{
+ {
+ name: "function with ANTLR-based extraction",
+ definition: `CREATE OR REPLACE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;`,
+ wantBody: " BEGIN RETURN a + b; END; ", // Expected content between dollar quotes
+ },
+ {
+ name: "procedure with ANTLR-based extraction",
+ definition: `CREATE OR REPLACE PROCEDURE update_counter() AS $$ BEGIN UPDATE counters SET count = count + 1; END; $$ LANGUAGE plpgsql;`,
+ wantBody: " BEGIN UPDATE counters SET count = count + 1; END; ", // Expected content between dollar quotes
+ },
+ {
+ name: "function with custom dollar tag",
+ definition: `CREATE OR REPLACE FUNCTION test_func() RETURNS text AS $body$ BEGIN RETURN 'test'; END; $body$ LANGUAGE plpgsql;`,
+ wantBody: " BEGIN RETURN 'test'; END; ", // Expected content between dollar quotes
+ },
+ {
+ name: "procedure with custom dollar tag",
+ definition: `CREATE OR REPLACE PROCEDURE test_proc() AS $proc$ BEGIN UPDATE stats SET last_run = NOW(); END; $proc$ LANGUAGE plpgsql;`,
+ wantBody: " BEGIN UPDATE stats SET last_run = NOW(); END; ", // Expected content between dollar quotes
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ body := extractFunctionBody(tt.definition)
+ // Normalize whitespace for comparison
+ body = strings.TrimSpace(body)
+ wantBody := strings.TrimSpace(tt.wantBody)
+
+ if body != wantBody {
+ t.Errorf("extractFunctionBody() = %q, want %q", body, wantBody)
+ }
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.go
index 588407d7ce..a58b743902 100644
--- a/backend/plugin/schema/pg/generate_migration.go
+++ b/backend/plugin/schema/pg/generate_migration.go
@@ -5,6 +5,9 @@ import (
"slices"
"strings"
+ "github.com/antlr4-go/antlr/v4"
+ pgparser "github.com/bytebase/parser/postgresql"
+
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"
"github.com/bytebase/bytebase/backend/plugin/schema"
@@ -1299,20 +1302,30 @@ 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(";")
}
_, _ = out.WriteString("\n\n")
+
case schema.MetadataDiffActionAlter:
- // PostgreSQL requires CREATE OR REPLACE for functions
- _, _ = out.WriteString(funcDiff.NewFunction.Definition)
- if !strings.HasSuffix(strings.TrimSpace(funcDiff.NewFunction.Definition), ";") {
- _, _ = out.WriteString(";")
+ // 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
+ definition := convertToCreateOrReplace(funcDiff.NewFunction.Definition)
+
+ _, _ = out.WriteString(definition)
+ if !strings.HasSuffix(strings.TrimSpace(definition), ";") {
+ _, _ = out.WriteString(";")
+ }
+ _, _ = out.WriteString("\n\n")
}
- _, _ = out.WriteString("\n\n")
+
default:
- // Ignore other actions
+ // Ignore other actions like DROP (handled elsewhere)
}
return nil
}
@@ -2037,3 +2050,150 @@ func writeCommentOnType(out *strings.Builder, schema, typeName, comment string)
_, _ = out.WriteString(`;`)
_, _ = out.WriteString("\n")
}
+
+// convertToCreateOrReplace uses ANTLR parser to safely convert CREATE FUNCTION to CREATE OR REPLACE FUNCTION
+func convertToCreateOrReplace(definition string) string {
+ // Parse the SQL statement using ANTLR
+ inputStream := antlr.NewInputStream(definition)
+ lexer := pgparser.NewPostgreSQLLexer(inputStream)
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ parser := pgparser.NewPostgreSQLParser(stream)
+
+ // Parse the root
+ tree := parser.Root()
+ if tree == nil {
+ // If parsing fails, return original definition
+ return definition
+ }
+
+ // Create a visitor to find and modify CREATE FUNCTION statements
+ visitor := &CreateOrReplaceVisitor{
+ tokens: stream,
+ rewriter: antlr.NewTokenStreamRewriter(stream),
+ definition: definition,
+ }
+
+ // Visit the tree
+ visitor.Visit(tree)
+
+ // Get the modified text
+ interval := antlr.NewInterval(0, len(definition)-1)
+ result := visitor.rewriter.GetText("", interval)
+ if result == "" {
+ // If rewriting fails, return original definition
+ return definition
+ }
+
+ return result
+}
+
+// CreateOrReplaceVisitor visits the parse tree and modifies CREATE FUNCTION to CREATE OR REPLACE FUNCTION
+type CreateOrReplaceVisitor struct {
+ *pgparser.BasePostgreSQLParserVisitor
+ tokens *antlr.CommonTokenStream
+ rewriter *antlr.TokenStreamRewriter
+ definition string
+}
+
+// Visit implements the visitor pattern
+func (v *CreateOrReplaceVisitor) Visit(tree antlr.ParseTree) any {
+ switch t := tree.(type) {
+ case *pgparser.CreatefunctionstmtContext:
+ return v.visitCreateFunctionStmt(t)
+ default:
+ // Continue visiting children
+ return v.visitChildren(tree)
+ }
+}
+
+// visitChildren visits all children of a node
+func (v *CreateOrReplaceVisitor) visitChildren(node antlr.ParseTree) any {
+ for i := 0; i < node.GetChildCount(); i++ {
+ child := node.GetChild(i)
+ if parseTree, ok := child.(antlr.ParseTree); ok {
+ v.Visit(parseTree)
+ }
+ }
+ return nil
+}
+
+// visitCreateFunctionStmt handles CREATE FUNCTION statements
+func (v *CreateOrReplaceVisitor) visitCreateFunctionStmt(ctx *pgparser.CreatefunctionstmtContext) any {
+ if ctx == nil {
+ return nil
+ }
+
+ // Check if "OR REPLACE" already exists
+ if v.hasOrReplace(ctx) {
+ // Already has "OR REPLACE", no need to modify
+ return nil
+ }
+
+ // Find the CREATE token
+ createToken := ctx.GetStart()
+ if createToken == nil {
+ return nil
+ }
+
+ // Look for the FUNCTION keyword after CREATE
+ functionToken := v.findFunctionToken(ctx)
+ if functionToken == nil {
+ return nil
+ }
+
+ // Insert "OR REPLACE" between CREATE and FUNCTION
+ // We insert it right before the FUNCTION token
+ v.rewriter.InsertBefore("", functionToken.GetTokenIndex(), "OR REPLACE ")
+
+ return nil
+}
+
+// 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
+ start := ctx.GetStart().GetTokenIndex()
+ stop := ctx.GetStop().GetTokenIndex()
+
+ for i := start; i <= stop; i++ {
+ token := v.tokens.Get(i)
+ if token.GetTokenType() == pgparser.PostgreSQLParserFUNCTION {
+ return token
+ }
+ }
+
+ return nil
+}
+
+// hasOrReplace checks if the CREATE FUNCTION statement already contains "OR REPLACE"
+func (v *CreateOrReplaceVisitor) hasOrReplace(ctx *pgparser.CreatefunctionstmtContext) bool {
+ // Get all tokens in the context range between CREATE and FUNCTION
+ start := ctx.GetStart().GetTokenIndex()
+ functionToken := v.findFunctionToken(ctx)
+ if functionToken == nil {
+ return false
+ }
+ stop := functionToken.GetTokenIndex()
+
+ // Look for "OR" followed by "REPLACE" tokens, skipping whitespace
+ for i := start; i < stop; i++ {
+ token := v.tokens.Get(i)
+ if token.GetTokenType() == pgparser.PostgreSQLParserOR {
+ // Found OR, now look for REPLACE after it (skipping whitespace)
+ for j := i + 1; j < stop; j++ {
+ nextToken := v.tokens.Get(j)
+ // Skip whitespace tokens (channel 1 is hidden channel based on debug output)
+ if nextToken.GetChannel() == 1 {
+ continue
+ }
+ // Check if the next non-whitespace token is REPLACE
+ if nextToken.GetTokenType() == pgparser.PostgreSQLParserREPLACE {
+ return true
+ }
+ // If it's not REPLACE, this OR is not our OR REPLACE pattern
+ break
+ }
+ }
+ }
+
+ return false
+}
diff --git a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
index 5dbab38bd0..20f3034578 100644
--- a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
+++ b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
@@ -2076,6 +2076,140 @@ COMMENT ON TABLE test_table IS NULL;
`,
description: "Reverse of comments_with_special_characters: DROP comments with special chars",
},
+ {
+ name: "trigger_function_body_change",
+ initialSchema: `
+CREATE TABLE user_activity_log (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ action VARCHAR(50) NOT NULL,
+ details TEXT,
+ logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ last_login TIMESTAMP,
+ login_count INTEGER DEFAULT 0,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Function that will be used by trigger
+CREATE OR REPLACE FUNCTION log_user_login() RETURNS TRIGGER AS $$
+BEGIN
+ -- Original implementation: simple logging
+ INSERT INTO user_activity_log (user_id, action, details)
+ VALUES (NEW.id, 'login', 'User logged in at ' || NEW.last_login);
+
+ UPDATE users SET login_count = COALESCE(login_count, 0) + 1 WHERE id = NEW.id;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Trigger depending on the function
+CREATE TRIGGER user_login_trigger
+ AFTER UPDATE OF last_login ON users
+ FOR EACH ROW
+ WHEN (OLD.last_login IS DISTINCT FROM NEW.last_login AND NEW.last_login IS NOT NULL)
+ EXECUTE FUNCTION log_user_login();
+`,
+ migrationDDL: `
+-- Modify only the function body (keeping signature identical)
+CREATE OR REPLACE FUNCTION log_user_login() RETURNS TRIGGER AS $$
+BEGIN
+ -- Enhanced implementation: more detailed logging with additional checks
+ IF NEW.last_login IS NOT NULL THEN
+ INSERT INTO user_activity_log (user_id, action, details)
+ VALUES (NEW.id, 'login', 'User ' || NEW.username || ' logged in at ' || NEW.last_login || ' (previous: ' || COALESCE(OLD.last_login::text, 'never') || ')');
+
+ -- Update login count with better handling
+ UPDATE users
+ SET login_count = COALESCE(login_count, 0) + 1
+ WHERE id = NEW.id;
+
+ -- Log additional info for frequent users
+ IF NEW.login_count > 100 THEN
+ INSERT INTO user_activity_log (user_id, action, details)
+ VALUES (NEW.id, 'frequent_user', 'User has logged in more than 100 times');
+ END IF;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+`,
+ description: "Trigger depending on function with body-only change (should use CREATE OR REPLACE)",
+ },
+ {
+ name: "reverse_trigger_function_body_change",
+ initialSchema: `
+CREATE TABLE user_activity_log (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ action VARCHAR(50) NOT NULL,
+ details TEXT,
+ logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ last_login TIMESTAMP,
+ login_count INTEGER DEFAULT 0,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Enhanced function implementation (this is the "after" state)
+CREATE OR REPLACE FUNCTION log_user_login() RETURNS TRIGGER AS $$
+BEGIN
+ -- Enhanced implementation: more detailed logging with additional checks
+ IF NEW.last_login IS NOT NULL THEN
+ INSERT INTO user_activity_log (user_id, action, details)
+ VALUES (NEW.id, 'login', 'User ' || NEW.username || ' logged in at ' || NEW.last_login || ' (previous: ' || COALESCE(OLD.last_login::text, 'never') || ')');
+
+ -- Update login count with better handling
+ UPDATE users
+ SET login_count = COALESCE(login_count, 0) + 1
+ WHERE id = NEW.id;
+
+ -- Log additional info for frequent users
+ IF NEW.login_count > 100 THEN
+ INSERT INTO user_activity_log (user_id, action, details)
+ VALUES (NEW.id, 'frequent_user', 'User has logged in more than 100 times');
+ END IF;
+ END IF;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Trigger depending on the function
+CREATE TRIGGER user_login_trigger
+ AFTER UPDATE OF last_login ON users
+ FOR EACH ROW
+ WHEN (OLD.last_login IS DISTINCT FROM NEW.last_login AND NEW.last_login IS NOT NULL)
+ EXECUTE FUNCTION log_user_login();
+`,
+ migrationDDL: `
+-- Revert function to original simpler implementation
+CREATE OR REPLACE FUNCTION log_user_login() RETURNS TRIGGER AS $$
+BEGIN
+ -- Original implementation: simple logging
+ INSERT INTO user_activity_log (user_id, action, details)
+ VALUES (NEW.id, 'login', 'User logged in at ' || NEW.last_login);
+
+ UPDATE users SET login_count = COALESCE(login_count, 0) + 1 WHERE id = NEW.id;
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+`,
+ description: "Reverse of trigger_function_body_change: revert function body to original",
+ },
}
for _, tc := range testCases {
diff --git a/backend/plugin/schema/pg/get_database_metadata.go b/backend/plugin/schema/pg/get_database_metadata.go
index 770862a55e..a943ed736a 100644
--- a/backend/plugin/schema/pg/get_database_metadata.go
+++ b/backend/plugin/schema/pg/get_database_metadata.go
@@ -1542,7 +1542,7 @@ func (e *metadataExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
functionMetadata := &storepb.FunctionMetadata{
Name: funcName,
- Definition: e.normalizePostgreSQLFunctionDefinition(ctx),
+ Definition: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),
Signature: e.extractFunctionSignature(ctx, funcName),
}
@@ -1552,74 +1552,6 @@ func (e *metadataExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst
schemaMetadata.Functions = append(schemaMetadata.Functions, functionMetadata)
}
-// normalizePostgreSQLFunctionDefinition normalizes a PostgreSQL function definition
-// to match what PostgreSQL stores in its system catalogs
-func (*metadataExtractor) normalizePostgreSQLFunctionDefinition(ctx *parser.CreatefunctionstmtContext) string {
- rawDefinition := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)
-
- // Apply PostgreSQL-style normalization
- normalized := strings.ToLower(rawDefinition)
-
- // Normalize whitespace
- normalized = strings.ReplaceAll(normalized, "\n", " ")
- normalized = strings.ReplaceAll(normalized, "\t", " ")
-
- // Remove extra spaces
- for strings.Contains(normalized, " ") {
- normalized = strings.ReplaceAll(normalized, " ", " ")
- }
-
- // Change CREATE FUNCTION to CREATE OR REPLACE FUNCTION (PostgreSQL default behavior)
- if strings.HasPrefix(strings.TrimSpace(normalized), "create function") {
- normalized = strings.Replace(normalized, "create function", "create or replace function", 1)
- }
-
- // Normalize parameter types to match PostgreSQL's system catalog representation
- normalized = strings.ReplaceAll(normalized, "varchar", "character varying")
-
- // Normalize DECIMAL to NUMERIC (PostgreSQL's canonical representation)
- // Only normalize return types and parameters, not inside function bodies
- normalized = strings.ReplaceAll(normalized, "returns decimal", "returns numeric")
-
- // Normalize dollar quoting to $function$ style (PostgreSQL's preferred form)
- normalized = normalizeDollarQuotingToFunction(normalized)
-
- // Move LANGUAGE clause to the end if it's not already there
- normalized = moveLanguageToEnd(normalized)
-
- return strings.TrimSpace(normalized)
-}
-
-// normalizeDollarQuotingToFunction converts $$ to $function$ style quoting
-func normalizeDollarQuotingToFunction(s string) string {
- // Simple replacement - in a production system, you'd want more sophisticated parsing
- return strings.ReplaceAll(s, "$$", "$function$")
-}
-
-// moveLanguageToEnd moves the LANGUAGE clause to the correct position before AS clause
-func moveLanguageToEnd(definition string) string {
- // PostgreSQL stores functions with LANGUAGE before AS clause
- // Pattern: ...returns type language plpgsql as $function$...
-
- if !strings.Contains(definition, "language plpgsql") {
- return definition
- }
-
- // Remove existing language clause
- withoutLanguage := strings.ReplaceAll(definition, " language plpgsql", "")
- withoutLanguage = strings.ReplaceAll(withoutLanguage, "language plpgsql ", "")
-
- // Find the position to insert LANGUAGE before AS
- asIndex := strings.Index(withoutLanguage, " as $function$")
- if asIndex == -1 {
- // Fallback: add at the end
- return strings.TrimSpace(withoutLanguage) + " language plpgsql"
- }
-
- // Insert LANGUAGE before AS
- return withoutLanguage[:asIndex] + " language plpgsql" + withoutLanguage[asIndex:]
-}
-
// extractFunctionSignature extracts the function signature with parameter types
func (*metadataExtractor) extractFunctionSignature(ctx *parser.CreatefunctionstmtContext, funcName string) string {
var signature strings.Builder
diff --git a/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go
index 6f62f5bdae..37e9745dff 100644
--- a/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go
+++ b/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go
@@ -1391,10 +1391,24 @@ func compareFunctions(t *testing.T, syncFuncs, parseFuncs []*storepb.FunctionMet
require.NotNil(t, syncFn, "function with signature %s should exist in sync metadata", parseFn.Signature)
- // Compare function definitions
- syncDef := normalizeSQL(syncFn.Definition)
- parseDef := normalizeSQL(parseFn.Definition)
- require.Equal(t, syncDef, parseDef, "function %s: definition should match", parseFn.Name)
+ // Compare function definitions using PostgreSQL function comparer
+ comparer := &PostgreSQLFunctionComparer{}
+ syncFunc := &model.FunctionMetadata{Definition: syncFn.Definition}
+ parseFunc := &model.FunctionMetadata{Definition: parseFn.Definition}
+
+ // Use function comparer to check if they are equal
+ if !comparer.Equal(syncFunc, parseFunc) {
+ // Get detailed comparison for better error message
+ result, err := comparer.CompareDetailed(syncFunc, parseFunc)
+ if err != nil {
+ t.Errorf("function %s: error comparing functions: %v", parseFn.Name, err)
+ } else if result != nil {
+ t.Errorf("function %s: definitions differ - SignatureChanged: %v, BodyChanged: %v, AttributesChanged: %v",
+ parseFn.Name, result.SignatureChanged, result.BodyChanged, result.AttributesChanged)
+ t.Logf(" Sync definition: %s", syncFn.Definition)
+ t.Logf(" Parse definition: %s", parseFn.Definition)
+ }
+ }
// Compare comment if present
if syncFn.Comment != "" || parseFn.Comment != "" {
@@ -1816,6 +1830,15 @@ func validateWithSchemaDiffer(t *testing.T, testName string, syncMeta, parseMeta
diffMessages = append(diffMessages, fmt.Sprintf("%d function changes", len(diff.FunctionChanges)))
for _, change := range diff.FunctionChanges {
t.Logf("Function change: %s %s.%s", change.Action, change.SchemaName, change.FunctionName)
+ // Log detailed function comparison for debugging
+ if change.OldFunction != nil && change.NewFunction != nil {
+ t.Logf(" Old function signature: %s", change.OldFunction.Signature)
+ t.Logf(" New function signature: %s", change.NewFunction.Signature)
+ t.Logf(" Old function definition: %s", change.OldFunction.Definition)
+ t.Logf(" New function definition: %s", change.NewFunction.Definition)
+ t.Logf(" Definitions equal: %v", change.OldFunction.Definition == change.NewFunction.Definition)
+ t.Logf(" Signatures equal: %v", change.OldFunction.Signature == change.NewFunction.Signature)
+ }
}
}