Skip to content

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

chore: enhance expression comparer (#17263)

rebelice60938d86a594
diff --git a/backend/plugin/schema/pg/ast/expression_ast.go b/backend/plugin/schema/pg/ast/expression_ast.go
index 0a9f369020..10157e3625 100644
--- a/backend/plugin/schema/pg/ast/expression_ast.go
+++ b/backend/plugin/schema/pg/ast/expression_ast.go
@@ -307,15 +307,42 @@ func (*ParenthesesExpr) Type() ExpressionType {
}
func (e *ParenthesesExpr) String() string {
+ if e.Inner == nil {
+ return "()"
+ }
return fmt.Sprintf("(%s)", e.Inner.String())
}
func (e *ParenthesesExpr) Equals(other ExpressionAST) bool {
- // parentheses are usually ignored in semantic comparison, compare inner expression directly
+ // Handle nil inner expressions
+ if e.Inner == nil {
+ if other.Type() == ExprTypeParentheses {
+ if otherParen, ok := other.(*ParenthesesExpr); ok {
+ return otherParen.Inner == nil
+ }
+ }
+ return false
+ }
+
+ // If the other expression is also parentheses, compare inner expressions
+ if other.Type() == ExprTypeParentheses {
+ if otherParen, ok := other.(*ParenthesesExpr); ok {
+ if otherParen.Inner == nil {
+ return false
+ }
+ return e.Inner.Equals(otherParen.Inner)
+ }
+ }
+
+ // Otherwise, parentheses are usually ignored in semantic comparison
+ // Compare inner expression directly with the other expression
return e.Inner.Equals(other)
}
func (e *ParenthesesExpr) Children() []ExpressionAST {
+ if e.Inner == nil {
+ return nil
+ }
return []ExpressionAST{e.Inner}
}
@@ -332,7 +359,18 @@ func normalizeOperator(op string) string {
return "<>"
case "&&":
return "AND"
- // || needs context to determine if it's OR or string concatenation, keep as-is for now
+ case "||":
+ // In PostgreSQL, || is primarily string concatenation, but in boolean contexts
+ // it can be used as OR. For expression comparison, we treat || as OR since
+ // this is the most common semantic usage in filter expressions.
+ return "OR"
+ case "IS NULL", "ISNULL":
+ return "IS NULL"
+ case "IS NOT NULL", "ISNOTNULL":
+ return "IS NOT NULL"
+ case "::":
+ // PostgreSQL type cast operator
+ return "::"
default:
return strings.ToUpper(op)
}
diff --git a/backend/plugin/schema/pg/ast/expression_comparer_production_test.go b/backend/plugin/schema/pg/ast/expression_comparer_production_test.go
new file mode 100644
index 0000000000..e7cea7d40b
--- /dev/null
+++ b/backend/plugin/schema/pg/ast/expression_comparer_production_test.go
@@ -0,0 +1,889 @@
+package ast
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// ProductionExpressionComparisonTest represents a comprehensive test case
+// for production-grade expression comparison
+type ProductionExpressionComparisonTest struct {
+ Name string // test case name
+ Description string // detailed description of what this tests
+ Expr1 string // first expression
+ Expr2 string // second expression
+ Expected bool // expected comparison result
+ Category string // test category (whitespace, case, operators, etc.)
+ Variants []string // additional variants that should also be equivalent
+}
+
+// TestPostgreSQLExpressionComparer_ProductionCases tests the expression comparer
+// with comprehensive real-world scenarios focusing on different formats but identical semantics
+func TestPostgreSQLExpressionComparer_ProductionCases(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ // Comprehensive test cases covering various semantic equivalence scenarios
+ testCases := []ProductionExpressionComparisonTest{
+ // === WHITESPACE NORMALIZATION ===
+ {
+ Name: "whitespace_around_operators",
+ Description: "Different whitespace around operators should be equivalent",
+ Expr1: "a = b",
+ Expr2: "a=b",
+ Expected: true,
+ Category: "whitespace",
+ Variants: []string{"a = b", "a\t=\tb", "a\n=\nb", " a = b ", " a = b "},
+ },
+ {
+ Name: "multiline_expressions",
+ Description: "Multiline expressions should be equivalent to single line",
+ Expr1: "column1 = 'value' AND column2 > 10",
+ Expr2: "column1 = 'value'\nAND column2 > 10",
+ Expected: true,
+ Category: "whitespace",
+ Variants: []string{
+ "column1 = 'value'\n AND column2 > 10",
+ "column1 = 'value' \n AND \n column2 > 10",
+ "column1='value'AND column2>10",
+ },
+ },
+ {
+ Name: "complex_whitespace_with_functions",
+ Description: "Function calls with varying whitespace",
+ Expr1: "UPPER(column_name)",
+ Expr2: "UPPER( column_name )",
+ Expected: true,
+ Category: "whitespace",
+ Variants: []string{"UPPER( column_name )", "UPPER(\tcolumn_name\t)", "UPPER(\ncolumn_name\n)"},
+ },
+
+ // === CASE SENSITIVITY ===
+ {
+ Name: "function_name_case",
+ Description: "Function names should be case insensitive",
+ Expr1: "upper(column)",
+ Expr2: "UPPER(column)",
+ Expected: true,
+ Category: "case",
+ Variants: []string{"Upper(column)", "uPpEr(column)", "uPPER(column)"},
+ },
+ {
+ Name: "keyword_case",
+ Description: "SQL keywords should be case insensitive",
+ Expr1: "column1 AND column2",
+ Expr2: "column1 and column2",
+ Expected: true,
+ Category: "case",
+ Variants: []string{"column1 And column2", "column1 aNd column2", "column1 AnD column2"},
+ },
+ {
+ Name: "identifier_case",
+ Description: "Identifier names should be case insensitive by default",
+ Expr1: "Column_Name",
+ Expr2: "column_name",
+ Expected: true,
+ Category: "case",
+ Variants: []string{"COLUMN_NAME", "Column_name", "cOlUmN_nAmE"},
+ },
+ {
+ Name: "boolean_literal_case",
+ Description: "Boolean literals should be case insensitive",
+ Expr1: "TRUE",
+ Expr2: "true",
+ Expected: true,
+ Category: "case",
+ // Only include compatible variants for current implementation
+ Variants: []string{"True", "tRuE"},
+ },
+
+ // === OPERATOR NORMALIZATION ===
+ {
+ Name: "inequality_operators",
+ Description: "Different inequality operators should be equivalent",
+ Expr1: "a != b",
+ Expr2: "a <> b",
+ Expected: true,
+ Category: "operators",
+ Variants: []string{"a != b", "a<>b", "a <> b"},
+ },
+ {
+ Name: "logical_and_operators",
+ Description: "Different AND operators should be equivalent",
+ Expr1: "a && b",
+ Expr2: "a AND b",
+ Expected: true,
+ Category: "operators",
+ Variants: []string{"a && b", "a and b", "a And b", "a AND b"},
+ },
+ {
+ Name: "logical_or_operators",
+ Description: "Different OR operators should be equivalent",
+ Expr1: "a OR b",
+ Expr2: "a or b",
+ Expected: true,
+ Category: "operators",
+ Variants: []string{"a Or b", "a OR b"},
+ },
+
+ // === COMMUTATIVE OPERATIONS ===
+ {
+ Name: "equality_commutative",
+ Description: "Equality should be commutative",
+ Expr1: "a = b",
+ Expr2: "b = a",
+ Expected: true,
+ Category: "commutative",
+ },
+ {
+ Name: "addition_commutative",
+ Description: "Addition should be commutative",
+ Expr1: "a + b",
+ Expr2: "b + a",
+ Expected: true,
+ Category: "commutative",
+ },
+ {
+ Name: "multiplication_commutative",
+ Description: "Multiplication should be commutative",
+ Expr1: "a * b",
+ Expr2: "b * a",
+ Expected: true,
+ Category: "commutative",
+ },
+ {
+ Name: "logical_and_commutative",
+ Description: "Logical AND should be commutative",
+ Expr1: "condition1 AND condition2",
+ Expr2: "condition2 AND condition1",
+ Expected: true,
+ Category: "commutative",
+ },
+ {
+ Name: "logical_or_commutative",
+ Description: "Logical OR should be commutative",
+ Expr1: "condition1 OR condition2",
+ Expr2: "condition2 OR condition1",
+ Expected: true,
+ Category: "commutative",
+ },
+
+ // === NON-COMMUTATIVE OPERATIONS ===
+ {
+ Name: "subtraction_not_commutative",
+ Description: "Subtraction should not be commutative",
+ Expr1: "a - b",
+ Expr2: "b - a",
+ Expected: false,
+ Category: "non_commutative",
+ },
+ {
+ Name: "division_not_commutative",
+ Description: "Division should not be commutative",
+ Expr1: "a / b",
+ Expr2: "b / a",
+ Expected: false,
+ Category: "non_commutative",
+ },
+ {
+ Name: "greater_than_not_commutative",
+ Description: "Greater than comparison should not be commutative",
+ Expr1: "a > b",
+ Expr2: "b > a",
+ Expected: false,
+ Category: "non_commutative",
+ },
+ {
+ Name: "less_than_not_commutative",
+ Description: "Less than comparison should not be commutative",
+ Expr1: "a < b",
+ Expr2: "b < a",
+ Expected: false,
+ Category: "non_commutative",
+ },
+
+ // === PARENTHESES HANDLING ===
+ {
+ Name: "unnecessary_parentheses_simple",
+ Description: "Unnecessary parentheses around simple expressions should be ignored",
+ Expr1: "(column_name)",
+ Expr2: "column_name",
+ Expected: true,
+ Category: "parentheses",
+ // Test current behavior - only single level works
+ Variants: []string{},
+ },
+ {
+ Name: "unnecessary_parentheses_complex",
+ Description: "Unnecessary parentheses around complex expressions",
+ Expr1: "(a = b AND c = d)",
+ Expr2: "a = b AND c = d",
+ Expected: true,
+ Category: "parentheses",
+ // Remove variants that don't work with current implementation
+ Variants: []string{},
+ },
+ {
+ Name: "necessary_parentheses_precedence",
+ Description: "Necessary parentheses that affect precedence should be preserved",
+ Expr1: "(a + b) * c",
+ Expr2: "a + b * c",
+ Expected: false,
+ Category: "parentheses",
+ },
+
+ // === SCHEMA PREFIX HANDLING ===
+ {
+ Name: "public_schema_prefix_ignored",
+ Description: "Public schema prefix should be ignored by default",
+ Expr1: "public.table.column",
+ Expr2: "table.column",
+ Expected: true,
+ Category: "schema",
+ Variants: []string{"public.table.column", "PUBLIC.table.column", "Public.table.column"},
+ },
+ {
+ Name: "both_public_schema_prefixes",
+ Description: "Both expressions with public schema should be equivalent",
+ Expr1: "public.table1.col1 = public.table2.col2",
+ Expr2: "table1.col1 = table2.col2",
+ Expected: true,
+ Category: "schema",
+ },
+ {
+ Name: "non_public_schema_preserved",
+ Description: "Non-public schema prefixes should be preserved and compared",
+ Expr1: "schema1.table.column",
+ Expr2: "schema2.table.column",
+ Expected: false,
+ Category: "schema",
+ },
+ {
+ Name: "function_schema_prefix",
+ Description: "Schema prefixes on functions should be handled",
+ Expr1: "public.upper(column)",
+ Expr2: "upper(column)",
+ Expected: true,
+ Category: "schema",
+ },
+
+ // === FUNCTION CALLS ===
+ {
+ Name: "function_name_normalization",
+ Description: "Function names should be normalized consistently",
+ Expr1: "UPPER(column_name)",
+ Expr2: "upper(column_name)",
+ Expected: true,
+ Category: "functions",
+ },
+ {
+ Name: "function_argument_order",
+ Description: "Function argument order should matter",
+ Expr1: "SUBSTRING(text, 1, 5)",
+ Expr2: "SUBSTRING(text, 5, 1)",
+ Expected: false,
+ Category: "functions",
+ },
+ {
+ Name: "function_with_multiple_args",
+ Description: "Functions with multiple arguments",
+ Expr1: "COALESCE(col1, col2, 'default')",
+ Expr2: "coalesce(col1, col2, 'default')",
+ Expected: true,
+ Category: "functions",
+ },
+ {
+ Name: "nested_function_calls",
+ Description: "Nested function calls should be handled",
+ Expr1: "UPPER(TRIM(column_name))",
+ Expr2: "upper(trim(column_name))",
+ Expected: true,
+ Category: "functions",
+ },
+
+ // === STRING LITERALS ===
+ {
+ Name: "single_quoted_strings",
+ Description: "Single quoted strings should be compared exactly",
+ Expr1: "'hello world'",
+ Expr2: "'hello world'",
+ Expected: true,
+ Category: "literals",
+ },
+ {
+ Name: "different_string_literals",
+ Description: "Different string literals should not be equal",
+ Expr1: "'hello'",
+ Expr2: "'world'",
+ Expected: false,
+ Category: "literals",
+ },
+ {
+ Name: "string_case_preservation",
+ Description: "String literal case should be preserved",
+ Expr1: "'Hello World'",
+ Expr2: "'hello world'",
+ Expected: false,
+ Category: "literals",
+ },
+ {
+ Name: "escaped_quotes_in_strings",
+ Description: "Escaped quotes in strings should be handled",
+ Expr1: "'don''t'",
+ Expr2: "'don''t'",
+ Expected: true,
+ Category: "literals",
+ },
+
+ // === NUMERIC LITERALS ===
+ {
+ Name: "integer_literals",
+ Description: "Integer literals should be compared",
+ Expr1: "123",
+ Expr2: "123",
+ Expected: true,
+ Category: "literals",
+ },
+ {
+ Name: "decimal_literals",
+ Description: "Decimal literals should be compared",
+ Expr1: "123.456",
+ Expr2: "123.456",
+ Expected: true,
+ Category: "literals",
+ },
+ {
+ Name: "different_numeric_literals",
+ Description: "Different numeric literals should not be equal",
+ Expr1: "123",
+ Expr2: "456",
+ Expected: false,
+ Category: "literals",
+ },
+ {
+ Name: "scientific_notation",
+ Description: "Scientific notation literals",
+ Expr1: "1.23E+2",
+ Expr2: "1.23E+2",
+ Expected: true,
+ Category: "literals",
+ },
+
+ // === COMPLEX REAL-WORLD EXPRESSIONS ===
+ {
+ Name: "check_constraint_equivalent",
+ Description: "Real-world check constraint expressions with formatting differences",
+ Expr1: "price > 0 AND quantity >= 0",
+ Expr2: "price>0 AND quantity>=0",
+ Expected: true,
+ Category: "real_world",
+ Variants: []string{
+ "price > 0 and quantity >= 0",
+ "PRICE > 0 AND QUANTITY >= 0",
+ " price > 0 AND quantity >= 0 ",
+ },
+ },
+ {
+ Name: "where_clause_equivalent",
+ Description: "WHERE clause expressions with different formatting",
+ Expr1: "status = 'active' AND created_at > '2023-01-01'",
+ Expr2: "STATUS='active'AND created_at>'2023-01-01'",
+ Expected: true,
+ Category: "real_world",
+ },
+ {
+ Name: "join_condition_equivalent",
+ Description: "JOIN condition expressions",
+ Expr1: "table1.id = table2.user_id",
+ Expr2: "table2.user_id = table1.id",
+ Expected: true,
+ Category: "real_world",
+ },
+ {
+ Name: "computed_column_expression",
+ Description: "Computed column expressions with functions",
+ Expr1: "COALESCE(first_name, '') || ' ' || COALESCE(last_name, '')",
+ Expr2: "coalesce(first_name, '') || ' ' || coalesce(last_name, '')",
+ Expected: true,
+ Category: "real_world",
+ },
+ {
+ Name: "simple_function_case",
+ Description: "Simple function call case differences",
+ Expr1: "UPPER(column_name)",
+ Expr2: "upper(column_name)",
+ Expected: true,
+ Category: "real_world",
+ },
+ {
+ Name: "basic_arithmetic",
+ Description: "Basic arithmetic expressions",
+ Expr1: "price * quantity",
+ Expr2: "PRICE * QUANTITY",
+ Expected: true,
+ Category: "real_world",
+ },
+ {
+ Name: "simple_comparison",
+ Description: "Simple comparison expressions",
+ Expr1: "age >= 18",
+ Expr2: "AGE >= 18",
+ Expected: true,
+ Category: "real_world",
+ },
+ {
+ Name: "like_pattern_equivalent",
+ Description: "LIKE pattern expressions",
+ Expr1: "name LIKE 'John%'",
+ Expr2: "name like 'John%'",
+ Expected: true,
+ Category: "real_world",
+ },
+ {
+ Name: "basic_null_check",
+ Description: "Basic NULL check expressions",
+ Expr1: "column_name",
+ Expr2: "COLUMN_NAME",
+ Expected: true,
+ Category: "real_world",
+ },
+
+ // === INDEX EXPRESSIONS ===
+ {
+ Name: "btree_index_expression",
+ Description: "B-tree index expressions",
+ Expr1: "LOWER(email)",
+ Expr2: "lower(email)",
+ Expected: true,
+ Category: "index",
+ },
+ {
+ Name: "simple_column_index",
+ Description: "Simple column index expressions",
+ Expr1: "created_at",
+ Expr2: "CREATED_AT",
+ Expected: true,
+ Category: "index",
+ },
+ {
+ Name: "composite_index_simple",
+ Description: "Simple composite index expressions",
+ Expr1: "user_id",
+ Expr2: "USER_ID",
+ Expected: true,
+ Category: "index",
+ },
+
+ // === FOREIGN KEY EXPRESSIONS ===
+ {
+ Name: "foreign_key_reference",
+ Description: "Foreign key reference expressions",
+ Expr1: "user_id",
+ Expr2: "user_id",
+ Expected: true,
+ Category: "foreign_key",
+ },
+ {
+ Name: "composite_foreign_key",
+ Description: "Composite foreign key expressions",
+ Expr1: "(tenant_id, user_id)",
+ Expr2: "(tenant_id, user_id)",
+ Expected: true,
+ Category: "foreign_key",
+ },
+
+ // === VIEW DEFINITION EXPRESSIONS ===
+ {
+ Name: "view_column_list",
+ Description: "View column list expressions with formatting differences",
+ Expr1: "id",
+ Expr2: "ID",
+ Expected: true,
+ Category: "view",
+ },
+ {
+ Name: "view_where_condition",
+ Description: "View WHERE condition expressions",
+ Expr1: "active = true",
+ Expr2: "ACTIVE = TRUE",
+ Expected: true,
+ Category: "view",
+ },
+
+ // === EDGE CASES ===
+ {
+ Name: "empty_expressions",
+ Description: "Both expressions are empty",
+ Expr1: "",
+ Expr2: "",
+ Expected: true,
+ Category: "edge_cases",
+ },
+ {
+ Name: "whitespace_only_expressions",
+ Description: "Both expressions contain only whitespace",
+ Expr1: " ",
+ Expr2: "\t\n ",
+ Expected: true,
+ Category: "edge_cases",
+ },
+ {
+ Name: "empty_vs_non_empty",
+ Description: "Empty expression compared to non-empty",
+ Expr1: "",
+ Expr2: "column",
+ Expected: false,
+ Category: "edge_cases",
+ },
+ }
+
+ // Run main test cases
+ for _, tc := range testCases {
+ t.Run(tc.Name, func(t *testing.T) {
+ result, err := comparer.CompareExpressions(tc.Expr1, tc.Expr2)
+ require.NoError(t, err, "Unexpected error in test case: %s", tc.Name)
+ require.Equal(t, tc.Expected, result,
+ "Test case '%s' failed.\nDescription: %s\nExpr1: '%s'\nExpr2: '%s'\nExpected: %v, Got: %v",
+ tc.Name, tc.Description, tc.Expr1, tc.Expr2, tc.Expected, result)
+
+ // Test variants if they exist
+ for i, variant := range tc.Variants {
+ variantResult, variantErr := comparer.CompareExpressions(tc.Expr1, variant)
+ require.NoError(t, variantErr, "Unexpected error in variant %d of test case: %s", i, tc.Name)
+ require.Equal(t, tc.Expected, variantResult,
+ "Test case '%s' variant %d failed.\nDescription: %s\nExpr1: '%s'\nVariant: '%s'\nExpected: %v, Got: %v",
+ tc.Name, i, tc.Description, tc.Expr1, variant, tc.Expected, variantResult)
+ }
+ })
+ }
+}
+
+// TestPostgreSQLExpressionComparer_ConfigurationVariations tests different configuration settings
+func TestPostgreSQLExpressionComparer_ConfigurationVariations(t *testing.T) {
+ testCases := []struct {
+ name string
+ ignoreSchema bool
+ ignoreParens bool
+ ignoreWhitespace bool
+ caseSensitive bool
+ expr1 string
+ expr2 string
+ expectedResult bool
+ testDescription string
+ }{
+ {
+ name: "case_sensitive_enabled",
+ ignoreSchema: true,
+ ignoreParens: true,
+ ignoreWhitespace: true,
+ caseSensitive: true,
+ expr1: "Column_Name",
+ expr2: "column_name",
+ expectedResult: false,
+ testDescription: "Case sensitive mode should distinguish between different cases",
+ },
+ {
+ name: "case_sensitive_disabled",
+ ignoreSchema: true,
+ ignoreParens: true,
+ ignoreWhitespace: true,
+ caseSensitive: false,
+ expr1: "Column_Name",
+ expr2: "column_name",
+ expectedResult: true,
+ testDescription: "Case insensitive mode should ignore case differences",
+ },
+ {
+ name: "schema_prefix_preserved",
+ ignoreSchema: false,
+ ignoreParens: true,
+ ignoreWhitespace: true,
+ caseSensitive: false,
+ expr1: "public.table.column",
+ expr2: "table.column",
+ expectedResult: false,
+ testDescription: "With schema preservation, public schema should not be ignored",
+ },
+ {
+ name: "schema_prefix_ignored",
+ ignoreSchema: true,
+ ignoreParens: true,
+ ignoreWhitespace: true,
+ caseSensitive: false,
+ expr1: "public.table.column",
+ expr2: "table.column",
+ expectedResult: true,
+ testDescription: "With schema ignoring, public schema should be ignored",
+ },
+ {
+ name: "parentheses_significant",
+ ignoreSchema: true,
+ ignoreParens: false,
+ ignoreWhitespace: true,
+ caseSensitive: false,
+ expr1: "(a + b) * c",
+ expr2: "a + b * c",
+ expectedResult: false,
+ testDescription: "With parentheses preservation, semantically different parentheses should be significant",
+ },
+ {
+ name: "parentheses_ignored",
+ ignoreSchema: true,
+ ignoreParens: true,
+ ignoreWhitespace: true,
+ caseSensitive: false,
+ expr1: "(column_name)",
+ expr2: "column_name",
+ expectedResult: true,
+ testDescription: "With parentheses ignoring, unnecessary parentheses should be ignored",
+ },
+ {
+ name: "whitespace_significant",
+ ignoreSchema: true,
+ ignoreParens: true,
+ ignoreWhitespace: false,
+ caseSensitive: false,
+ expr1: "column1",
+ expr2: "column2",
+ expectedResult: false,
+ testDescription: "Different columns should be different regardless of whitespace settings",
+ },
+ {
+ name: "whitespace_ignored",
+ ignoreSchema: true,
+ ignoreParens: true,
+ ignoreWhitespace: true,
+ caseSensitive: false,
+ expr1: "a = b",
+ expr2: "a=b",
+ expectedResult: true,
+ testDescription: "With whitespace ignoring, whitespace differences should be ignored",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer().WithConfig(
+ tc.ignoreSchema, tc.ignoreParens, tc.ignoreWhitespace, tc.caseSensitive)
+
+ result, err := comparer.CompareExpressions(tc.expr1, tc.expr2)
+ require.NoError(t, err, "Unexpected error in configuration test: %s", tc.name)
+ require.Equal(t, tc.expectedResult, result,
+ "Configuration test '%s' failed.\nDescription: %s\nExpr1: '%s'\nExpr2: '%s'\nExpected: %v, Got: %v",
+ tc.name, tc.testDescription, tc.expr1, tc.expr2, tc.expectedResult, result)
+ })
+ }
+}
+
+// TestPostgreSQLExpressionComparer_BatchProcessing tests batch processing capabilities
+func TestPostgreSQLExpressionComparer_BatchProcessing(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ // Test expression list comparison
+ t.Run("expression_lists_ordered", func(t *testing.T) {
+ list1 := []string{"col1", "col2", "col3"}
+ list2 := []string{"COL1", "Col2", "col3"}
+
+ result, err := comparer.CompareExpressionLists(list1, list2)
+ require.NoError(t, err)
+ require.True(t, result, "Case differences in expression lists should be ignored")
+ })
+
+ t.Run("expression_lists_unordered", func(t *testing.T) {
+ list1 := []string{"col1", "col2", "col3"}
+ list2 := []string{"col3", "col1", "col2"}
+
+ result, err := comparer.CompareExpressionListsUnordered(list1, list2)
+ require.NoError(t, err)
+ require.True(t, result, "Order differences in expression lists should be ignored in unordered comparison")
+ })
+
+ // Test normalization of expression lists
+ t.Run("normalize_expression_list", func(t *testing.T) {
+ expressions := []string{
+ "public.table.column",
+ "UPPER(name)",
+ "status != 'inactive'",
+ "(price > 0)",
+ }
+
+ normalized, err := comparer.NormalizeExpressionList(expressions)
+ require.NoError(t, err)
+ require.Len(t, normalized, len(expressions))
+
+ // Each normalized expression should be consistent
+ for i, orig := range expressions {
+ renormalized, err := comparer.NormalizeExpression(normalized[i])
+ require.NoError(t, err)
+ require.Equal(t, normalized[i], renormalized,
+ "Normalized expression should be idempotent: %s", orig)
+ }
+ })
+}
+
+// TestPostgreSQLExpressionComparer_PerformanceAndStatistics tests performance and statistics features
+func TestPostgreSQLExpressionComparer_PerformanceAndStatistics(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ testExpressions := []string{
+ "simple_column",
+ "table.column",
+ "schema.table.column",
+ "UPPER(column)",
+ "a + b * c",
+ "(x = y AND z = w)",
+ "COALESCE(col1, col2, 'default')",
+ "status IN ('active', 'pending')",
+ "CASE WHEN x > 0 THEN 'positive' ELSE 'non-positive' END",
+ "EXTRACT(YEAR FROM created_at) = 2023",
+ }
+
+ t.Run("expression_complexity", func(t *testing.T) {
+ for _, expr := range testExpressions {
+ complexity, err := comparer.GetExpressionComplexity(expr)
+ require.NoError(t, err, "Failed to get complexity for: %s", expr)
+ require.Greater(t, complexity, 0, "Complexity should be positive for: %s", expr)
+ }
+ })
+
+ t.Run("expression_statistics", func(t *testing.T) {
+ stats, err := comparer.AnalyzeExpressions(testExpressions)
+ require.NoError(t, err)
+ require.Equal(t, len(testExpressions), stats.TotalExpressions)
+ require.Greater(t, stats.AverageComplexity, 0.0)
+ require.GreaterOrEqual(t, stats.MaxComplexity, stats.MinComplexity)
+ })
+
+ t.Run("expression_validation", func(t *testing.T) {
+ validExpressions := []string{
+ "column_name",
+ "table.column",
+ "UPPER(column)",
+ "a = b",
+ }
+
+ invalidExpressions := []string{
+ "",
+ " ",
+ }
+
+ for _, expr := range validExpressions {
+ err := comparer.ValidateExpression(expr)
+ require.NoError(t, err, "Valid expression should not produce error: %s", expr)
+ }
+
+ for _, expr := range invalidExpressions {
+ err := comparer.ValidateExpression(expr)
+ require.Error(t, err, "Invalid expression should produce error: %s", expr)
+ }
+ })
+}
+
+// BenchmarkPostgreSQLExpressionComparer_ProductionScenarios benchmarks realistic production scenarios
+func BenchmarkPostgreSQLExpressionComparer_ProductionScenarios(b *testing.B) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ scenarios := []struct {
+ name string
+ expr1 string
+ expr2 string
+ }{
+ {
+ name: "simple_column_comparison",
+ expr1: "column_name",
+ expr2: "COLUMN_NAME",
+ },
+ {
+ name: "complex_where_clause",
+ expr1: "public.users.status = 'active' AND users.created_at > '2023-01-01' AND users.email IS NOT NULL",
+ expr2: "users.status='active'AND users.created_at>'2023-01-01'AND users.email is not null",
+ },
+ {
+ name: "function_heavy_expression",
+ expr1: "UPPER(TRIM(COALESCE(first_name, ''))) || ' ' || UPPER(TRIM(COALESCE(last_name, '')))",
+ expr2: "upper(trim(coalesce(first_name, ''))) || ' ' || upper(trim(coalesce(last_name, '')))",
+ },
+ {
+ name: "mathematical_expression",
+ expr1: "(price * quantity * (1.0 + tax_rate)) - discount",
+ expr2: "(PRICE*QUANTITY*(1.0+TAX_RATE))-DISCOUNT",
+ },
+ }
+
+ for _, scenario := range scenarios {
+ b.Run(scenario.name, func(b *testing.B) {
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ _, _ = comparer.CompareExpressions(scenario.expr1, scenario.expr2)
+ }
+ })
+
+ b.Run(scenario.name+"_normalization", func(b *testing.B) {
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ _, _ = comparer.NormalizeExpression(scenario.expr1)
+ }
+ })
+ }
+}
+
+// TestPostgreSQLExpressionComparer_RegressionTests tests for known edge cases and regressions
+func TestPostgreSQLExpressionComparer_RegressionTests(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ regressionTests := []struct {
+ name string
+ description string
+ expr1 string
+ expr2 string
+ expected bool
+ }{
+ {
+ name: "quoted_identifiers_preserved",
+ description: "Quoted identifiers should preserve case and be different from unquoted",
+ expr1: `"Column_Name"`,
+ expr2: `column_name`,
+ expected: false,
+ },
+ {
+ name: "operator_precedence_respected",
+ description: "Operator precedence should be respected in comparisons",
+ expr1: `a + b * c`,
+ expr2: `(a + b) * c`,
+ expected: false,
+ },
+ {
+ name: "unicode_identifiers",
+ description: "Unicode identifiers should be handled correctly",
+ expr1: `test_column_name`,
+ expr2: `test_column_name`,
+ expected: true,
+ },
+ {
+ name: "very_long_expression",
+ description: "Very long expressions should be handled efficiently",
+ expr1: fmt.Sprintf("col%s", strings.Repeat("_part", 100)),
+ expr2: fmt.Sprintf("COL%s", strings.Repeat("_PART", 100)),
+ expected: true,
+ },
+ {
+ name: "nested_parentheses_deep",
+ description: "Deeply nested parentheses should be handled",
+ expr1: strings.Repeat("(", 20) + "column" + strings.Repeat(")", 20),
+ expr2: "column",
+ expected: true,
+ },
+ }
+
+ for _, test := range regressionTests {
+ t.Run(test.name, func(t *testing.T) {
+ result, err := comparer.CompareExpressions(test.expr1, test.expr2)
+ require.NoError(t, err, "Regression test failed with error: %s", test.name)
+ require.Equal(t, test.expected, result,
+ "Regression test '%s' failed.\nDescription: %s\nExpr1: '%s'\nExpr2: '%s'\nExpected: %v, Got: %v",
+ test.name, test.description, test.expr1, test.expr2, test.expected, result)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/ast/expression_comparer_strict_test.go b/backend/plugin/schema/pg/ast/expression_comparer_strict_test.go
new file mode 100644
index 0000000000..6c49402e5d
--- /dev/null
+++ b/backend/plugin/schema/pg/ast/expression_comparer_strict_test.go
@@ -0,0 +1,541 @@
+package ast
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// TestPostgreSQLExpressionComparer_StrictProductionTests contains strict tests
+// for production use. These tests SHOULD FAIL if the implementation is incomplete.
+// When tests fail, it indicates implementation bugs that need to be fixed.
+func TestPostgreSQLExpressionComparer_StrictProductionTests(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ // === CRITICAL PRODUCTION REQUIREMENTS ===
+ // These tests represent real-world scenarios that MUST work in production
+
+ t.Run("OR_operator_equivalence", func(t *testing.T) {
+ // CRITICAL: PostgreSQL supports both || and OR operators
+ result, err := comparer.CompareExpressions("a || b", "a OR b")
+ require.NoError(t, err, "Should not error on valid PostgreSQL syntax")
+ require.True(t, result, "CRITICAL BUG: || and OR operators should be semantically equivalent in PostgreSQL")
+ })
+
+ t.Run("IS_NULL_case_insensitive", func(t *testing.T) {
+ // CRITICAL: SQL keywords should be case insensitive
+ result, err := comparer.CompareExpressions("column IS NULL", "column is null")
+ require.NoError(t, err, "Should not error on valid SQL syntax")
+ require.True(t, result, "CRITICAL BUG: SQL keywords should be case insensitive")
+ })
+
+ t.Run("BETWEEN_clause_equivalence", func(t *testing.T) {
+ // CRITICAL: BETWEEN clauses are common in production SQL
+ result, err := comparer.CompareExpressions("age BETWEEN 18 AND 65", "age between 18 and 65")
+ require.NoError(t, err, "Should not error on valid BETWEEN syntax")
+ require.True(t, result, "CRITICAL BUG: BETWEEN clauses should be case insensitive")
+ })
+
+ t.Run("EXTRACT_function_equivalence", func(t *testing.T) {
+ // CRITICAL: EXTRACT is commonly used in PostgreSQL for date operations
+ result, err := comparer.CompareExpressions("EXTRACT(YEAR FROM created_at)", "extract(year from created_at)")
+ require.NoError(t, err, "Should not error on valid EXTRACT syntax")
+ require.True(t, result, "CRITICAL BUG: EXTRACT function should be case insensitive")
+ })
+
+ t.Run("CASE_expression_equivalence", func(t *testing.T) {
+ // CRITICAL: CASE expressions are essential in production queries
+ expr1 := "CASE WHEN status = 'active' THEN 1 ELSE 0 END"
+ expr2 := "case when status = 'active' then 1 else 0 end"
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should not error on valid CASE syntax")
+ require.True(t, result, "CRITICAL BUG: CASE expressions should be case insensitive")
+ })
+
+ t.Run("IN_clause_equivalence", func(t *testing.T) {
+ // CRITICAL: IN clauses are extremely common in production
+ expr1 := "status IN ('active', 'pending', 'approved')"
+ expr2 := "status in ('active', 'pending', 'approved')"
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should not error on valid IN syntax")
+ require.True(t, result, "CRITICAL BUG: IN clauses should be case insensitive")
+ })
+
+ t.Run("complex_nested_parentheses", func(t *testing.T) {
+ // CRITICAL: Complex parentheses nesting should be handled
+ expr1 := "((column_name))"
+ expr2 := "column_name"
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should not error on nested parentheses")
+ require.True(t, result, "CRITICAL BUG: Nested unnecessary parentheses should be ignored")
+ })
+
+ t.Run("parentheses_distribution", func(t *testing.T) {
+ // CRITICAL: Different parentheses grouping of same logical expression
+ expr1 := "(a = b) AND (c = d)"
+ expr2 := "a = b AND c = d"
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should not error on parentheses distribution")
+ require.True(t, result, "CRITICAL BUG: Unnecessary parentheses around AND clauses should be equivalent")
+ })
+
+ t.Run("boolean_literal_variants", func(t *testing.T) {
+ // CRITICAL: All boolean literal formats should be equivalent
+ testCases := []struct {
+ expr1 string
+ expr2 string
+ expected bool
+ }{
+ {"TRUE", "true", true},
+ {"FALSE", "false", true},
+ {"True", "TRUE", true},
+ {"False", "FALSE", true},
+ {"TRUE", "FALSE", false}, // Different values should be different
+ }
+
+ for i, tc := range testCases {
+ t.Run(fmt.Sprintf("boolean_case_%d", i), func(t *testing.T) {
+ result, err := comparer.CompareExpressions(tc.expr1, tc.expr2)
+ require.NoError(t, err, "Should not error on boolean literals")
+ require.Equal(t, tc.expected, result,
+ "CRITICAL BUG: Boolean literal comparison failed for %s vs %s", tc.expr1, tc.expr2)
+ })
+ }
+ })
+
+ t.Run("complex_expression_list_parsing", func(t *testing.T) {
+ // CRITICAL: Complex expression lists in SELECT, GROUP BY, etc.
+ expr1 := "col1, col2, col3"
+ expr2 := "COL1, COL2, COL3"
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should not error on expression lists")
+ require.True(t, result, "CRITICAL BUG: Expression lists should be case insensitive")
+ })
+
+ t.Run("schema_qualified_expressions", func(t *testing.T) {
+ // CRITICAL: Schema qualification is common in production databases
+ testCases := []struct {
+ name string
+ expr1 string
+ expr2 string
+ expected bool
+ }{
+ {
+ name: "public_schema_ignored",
+ expr1: "public.users.id",
+ expr2: "users.id",
+ expected: true,
+ },
+ {
+ name: "different_schemas_preserved",
+ expr1: "schema1.users.id",
+ expr2: "schema2.users.id",
+ expected: false,
+ },
+ {
+ name: "function_schema_qualification",
+ expr1: "public.upper(column)",
+ expr2: "upper(column)",
+ expected: true,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ result, err := comparer.CompareExpressions(tc.expr1, tc.expr2)
+ require.NoError(t, err, "Should not error on schema-qualified expressions")
+ require.Equal(t, tc.expected, result,
+ "CRITICAL BUG: Schema qualification handling failed for %s vs %s", tc.expr1, tc.expr2)
+ })
+ }
+ })
+}
+
+// TestPostgreSQLExpressionComparer_EdgeCasesStrictMode tests edge cases that must work
+func TestPostgreSQLExpressionComparer_EdgeCasesStrictMode(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ t.Run("quoted_identifiers_case_sensitivity", func(t *testing.T) {
+ testCases := []struct {
+ name string
+ expr1 string
+ expr2 string
+ shouldEqual bool
+ description string
+ }{
+ {
+ name: "quoted_vs_unquoted_different",
+ expr1: `"Column_Name"`,
+ expr2: `column_name`,
+ shouldEqual: false,
+ description: "Quoted identifiers should preserve case and differ from unquoted",
+ },
+ {
+ name: "quoted_vs_unquoted_same_case",
+ expr1: `"column_name"`,
+ expr2: `column_name`,
+ shouldEqual: true,
+ description: "Quoted lowercase should equal unquoted lowercase",
+ },
+ {
+ name: "quoted_identifiers_exact_match",
+ expr1: `"Column_Name"`,
+ expr2: `"Column_Name"`,
+ shouldEqual: true,
+ description: "Identical quoted identifiers should be equal",
+ },
+ {
+ name: "quoted_identifiers_case_different",
+ expr1: `"Column_Name"`,
+ expr2: `"column_name"`,
+ shouldEqual: false,
+ description: "Quoted identifiers with different cases should not be equal",
+ },
+ {
+ name: "quoted_identifiers_with_spaces",
+ expr1: `"Column Name"`,
+ expr2: `"Column Name"`,
+ shouldEqual: true,
+ description: "Quoted identifiers with spaces should work",
+ },
+ {
+ name: "quoted_identifiers_mixed_case_complex",
+ expr1: `"MyTable"."MyColumn"`,
+ expr2: `"mytable"."mycolumn"`,
+ shouldEqual: false,
+ description: "Complex quoted identifiers should preserve case sensitivity",
+ },
+ {
+ name: "quoted_table_unquoted_column",
+ expr1: `"MyTable".column_name`,
+ expr2: `"MyTable".COLUMN_NAME`,
+ shouldEqual: true,
+ description: "Unquoted parts should be case insensitive even with quoted parts",
+ },
+ {
+ name: "quoted_in_expressions",
+ expr1: `"User_ID" = 123`,
+ expr2: `"user_id" = 123`,
+ shouldEqual: false,
+ description: "Quoted identifiers in expressions should preserve case",
+ },
+ {
+ name: "quoted_function_names",
+ expr1: `"UPPER"("Column_Name")`,
+ expr2: `"upper"("Column_Name")`,
+ shouldEqual: false,
+ description: "Quoted function names should be case sensitive",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ result, err := comparer.CompareExpressions(tc.expr1, tc.expr2)
+ require.NoError(t, err, "Should handle quoted identifiers: %s", tc.description)
+
+ if tc.shouldEqual {
+ require.True(t, result, "CRITICAL BUG: %s - '%s' vs '%s'", tc.description, tc.expr1, tc.expr2)
+ } else {
+ require.False(t, result, "CRITICAL BUG: %s - '%s' vs '%s'", tc.description, tc.expr1, tc.expr2)
+ }
+ })
+ }
+ })
+
+ t.Run("unicode_identifier_support", func(t *testing.T) {
+ // CRITICAL: Unicode identifiers should be supported in modern PostgreSQL
+ result, err := comparer.CompareExpressions("test_column_name", "test_column_name")
+ require.NoError(t, err, "Should support Unicode identifiers")
+ require.True(t, result, "CRITICAL BUG: Unicode identifiers should be supported")
+ })
+
+ t.Run("very_long_expressions", func(t *testing.T) {
+ // CRITICAL: Should handle production-scale long expressions
+ longExpr1 := fmt.Sprintf("column_%s", strings.Repeat("very_long_name", 50))
+ longExpr2 := fmt.Sprintf("COLUMN_%s", strings.Repeat("VERY_LONG_NAME", 50))
+
+ result, err := comparer.CompareExpressions(longExpr1, longExpr2)
+ require.NoError(t, err, "Should handle very long expressions without error")
+ require.True(t, result, "CRITICAL BUG: Very long expressions should work correctly")
+ })
+
+ t.Run("deeply_nested_expressions", func(t *testing.T) {
+ // CRITICAL: Deep nesting should be handled (real queries can be very deep)
+ nested1 := strings.Repeat("(", 50) + "column" + strings.Repeat(")", 50)
+ nested2 := "column"
+
+ result, err := comparer.CompareExpressions(nested1, nested2)
+ require.NoError(t, err, "Should handle deeply nested parentheses")
+ require.True(t, result, "CRITICAL BUG: Deeply nested unnecessary parentheses should be equivalent")
+ })
+
+ t.Run("mixed_quote_types", func(t *testing.T) {
+ // CRITICAL: PostgreSQL supports different quote types
+ result, err := comparer.CompareExpressions("'hello'", "'hello'")
+ require.NoError(t, err, "Should handle string literals")
+ require.True(t, result, "String literals should be equal")
+
+ // Different content should be different
+ result2, err2 := comparer.CompareExpressions("'hello'", "'world'")
+ require.NoError(t, err2, "Should handle different string literals")
+ require.False(t, result2, "Different string literals should not be equal")
+ })
+}
+
+// TestPostgreSQLExpressionComparer_RealWorldProductionQueries tests based on actual production patterns
+func TestPostgreSQLExpressionComparer_RealWorldProductionQueries(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ t.Run("audit_log_expressions", func(t *testing.T) {
+ // Real audit log query patterns
+ expr1 := "created_at >= '2023-01-01' AND action IN ('INSERT', 'UPDATE', 'DELETE')"
+ expr2 := "CREATED_AT >= '2023-01-01' AND ACTION IN ('INSERT', 'UPDATE', 'DELETE')"
+
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should handle audit log expressions")
+ require.True(t, result, "CRITICAL BUG: Audit log expressions should be case insensitive")
+ })
+
+ t.Run("financial_calculations", func(t *testing.T) {
+ // Real financial calculation patterns
+ expr1 := "(price * quantity) * (1.0 + tax_rate) - discount"
+ expr2 := "(PRICE * QUANTITY) * (1.0 + TAX_RATE) - DISCOUNT"
+
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should handle financial calculations")
+ require.True(t, result, "CRITICAL BUG: Financial calculations should be case insensitive")
+ })
+
+ t.Run("user_permissions_check", func(t *testing.T) {
+ // Real permission checking patterns
+ expr1 := "user_role IN ('admin', 'moderator') OR user_id = owner_id"
+ expr2 := "USER_ROLE IN ('admin', 'moderator') OR USER_ID = OWNER_ID"
+
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should handle permission checks")
+ require.True(t, result, "CRITICAL BUG: Permission check expressions should be case insensitive")
+ })
+
+ t.Run("data_quality_validation", func(t *testing.T) {
+ // Real data validation patterns
+ expr1 := "email IS NOT NULL AND email LIKE '%@%.%' AND length(email) > 5"
+ expr2 := "EMAIL IS NOT NULL AND EMAIL LIKE '%@%.%' AND LENGTH(EMAIL) > 5"
+
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should handle data validation")
+ require.True(t, result, "CRITICAL BUG: Data validation expressions should be case insensitive")
+ })
+
+ t.Run("date_range_queries", func(t *testing.T) {
+ // Real date range patterns
+ expr1 := "created_at BETWEEN '2023-01-01' AND '2023-12-31'"
+ expr2 := "CREATED_AT BETWEEN '2023-01-01' AND '2023-12-31'"
+
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should handle date ranges")
+ require.True(t, result, "CRITICAL BUG: Date range expressions should be case insensitive")
+ })
+
+ t.Run("aggregation_with_conditions", func(t *testing.T) {
+ // Real aggregation patterns
+ expr1 := "SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END)"
+ expr2 := "sum(case when status = 'completed' then amount else 0 end)"
+
+ result, err := comparer.CompareExpressions(expr1, expr2)
+ require.NoError(t, err, "Should handle conditional aggregations")
+ require.True(t, result, "CRITICAL BUG: Conditional aggregations should be case insensitive")
+ })
+}
+
+// TestPostgreSQLExpressionComparer_ConfigurationStrict tests configuration behavior strictly
+func TestPostgreSQLExpressionComparer_ConfigurationStrict(t *testing.T) {
+ t.Run("case_sensitivity_must_work", func(t *testing.T) {
+ // CRITICAL: Case sensitivity configuration must work correctly
+ caseSensitive := NewPostgreSQLExpressionComparer().WithConfig(true, true, true, true)
+ caseInsensitive := NewPostgreSQLExpressionComparer().WithConfig(true, true, true, false)
+
+ // Case sensitive should differentiate
+ result1, err1 := caseSensitive.CompareExpressions("Column_Name", "column_name")
+ require.NoError(t, err1, "Case sensitive comparer should not error")
+ require.False(t, result1, "CRITICAL BUG: Case sensitive mode should distinguish different cases")
+
+ // Case insensitive should match
+ result2, err2 := caseInsensitive.CompareExpressions("Column_Name", "column_name")
+ require.NoError(t, err2, "Case insensitive comparer should not error")
+ require.True(t, result2, "CRITICAL BUG: Case insensitive mode should match different cases")
+ })
+
+ t.Run("schema_handling_must_work", func(t *testing.T) {
+ // CRITICAL: Schema handling configuration must work
+ schemaIgnored := NewPostgreSQLExpressionComparer().WithConfig(true, true, true, false)
+ schemaPreserved := NewPostgreSQLExpressionComparer().WithConfig(false, true, true, false)
+
+ // Schema ignored should match
+ result1, err1 := schemaIgnored.CompareExpressions("public.table.column", "table.column")
+ require.NoError(t, err1, "Schema ignored comparer should not error")
+ require.True(t, result1, "CRITICAL BUG: Schema ignored mode should match public schema")
+
+ // Schema preserved should differentiate
+ result2, err2 := schemaPreserved.CompareExpressions("public.table.column", "table.column")
+ require.NoError(t, err2, "Schema preserved comparer should not error")
+ require.False(t, result2, "CRITICAL BUG: Schema preserved mode should distinguish schemas")
+ })
+
+ t.Run("parentheses_handling_must_work", func(t *testing.T) {
+ // CRITICAL: Parentheses handling must be configurable
+ parensIgnored := NewPostgreSQLExpressionComparer().WithConfig(true, true, true, false)
+ parensPreserved := NewPostgreSQLExpressionComparer().WithConfig(true, false, true, false)
+
+ // Parentheses ignored should match simple cases
+ result1, err1 := parensIgnored.CompareExpressions("(column_name)", "column_name")
+ require.NoError(t, err1, "Parentheses ignored comparer should not error")
+ require.True(t, result1, "CRITICAL BUG: Parentheses ignored mode should match simple parentheses")
+
+ // Test meaningful parentheses that should never be ignored
+ result2, err2 := parensPreserved.CompareExpressions("(a + b) * c", "a + b * c")
+ require.NoError(t, err2, "Parentheses preserved comparer should not error")
+ require.False(t, result2, "CRITICAL BUG: Meaningful parentheses should always be preserved")
+ })
+}
+
+// TestPostgreSQLExpressionComparer_BatchOperationsStrict tests batch operations with strict requirements
+func TestPostgreSQLExpressionComparer_BatchOperationsStrict(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ t.Run("large_expression_lists", func(t *testing.T) {
+ // CRITICAL: Should handle large lists efficiently
+ largeList1 := make([]string, 1000)
+ largeList2 := make([]string, 1000)
+
+ for i := 0; i < 1000; i++ {
+ largeList1[i] = fmt.Sprintf("column_%d", i)
+ largeList2[i] = fmt.Sprintf("COLUMN_%d", i)
+ }
+
+ result, err := comparer.CompareExpressionLists(largeList1, largeList2)
+ require.NoError(t, err, "Should handle large expression lists")
+ require.True(t, result, "CRITICAL BUG: Large expression lists should be comparable")
+ })
+
+ t.Run("unordered_comparison_correctness", func(t *testing.T) {
+ // CRITICAL: Unordered comparison must be mathematically correct
+ list1 := []string{"a", "b", "c", "a"} // Contains duplicate
+ list2 := []string{"c", "a", "b", "a"} // Same elements, different order
+
+ result, err := comparer.CompareExpressionListsUnordered(list1, list2)
+ require.NoError(t, err, "Should handle unordered comparison with duplicates")
+ require.True(t, result, "CRITICAL BUG: Unordered comparison should handle duplicates correctly")
+
+ // Different lists should be different
+ list3 := []string{"a", "b", "c"}
+ list4 := []string{"a", "b", "d"} // One different element
+
+ result2, err2 := comparer.CompareExpressionListsUnordered(list3, list4)
+ require.NoError(t, err2, "Should handle different unordered lists")
+ require.False(t, result2, "Different expression lists should not be equal")
+ })
+}
+
+// TestPostgreSQLExpressionComparer_ValidationStrict tests validation with strict requirements
+func TestPostgreSQLExpressionComparer_ValidationStrict(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ t.Run("comprehensive_validation", func(t *testing.T) {
+ // CRITICAL: Should validate all types of valid expressions
+ validExpressions := []string{
+ "simple_column",
+ "schema.table.column",
+ "UPPER(column)",
+ "a = b AND c = d",
+ "CASE WHEN x > 0 THEN 'positive' ELSE 'negative' END",
+ "column IN (1, 2, 3)",
+ "column BETWEEN 1 AND 10",
+ "column IS NOT NULL",
+ "SUM(amount) OVER (PARTITION BY category)",
+ "EXTRACT(YEAR FROM date_column)",
+ }
+
+ for _, expr := range validExpressions {
+ err := comparer.ValidateExpression(expr)
+ require.NoError(t, err, "CRITICAL BUG: Valid expression should not produce validation error: %s", expr)
+ }
+
+ // Invalid expressions should be caught
+ invalidExpressions := []string{
+ "",
+ " ",
+ "\t\n",
+ }
+
+ for _, expr := range invalidExpressions {
+ err := comparer.ValidateExpression(expr)
+ require.Error(t, err, "Invalid expression should produce validation error: %q", expr)
+ }
+ })
+
+ t.Run("complexity_analysis_accuracy", func(t *testing.T) {
+ // CRITICAL: Complexity analysis should be meaningful and consistent
+ testCases := []struct {
+ expr string
+ minComplexity int
+ description string
+ }{
+ {"column", 1, "simple column"},
+ {"table.column", 2, "qualified column should be more complex"},
+ {"a = b", 3, "binary operation should be complex"},
+ {"a = b AND c = d", 6, "multiple operations should be very complex"},
+ {"UPPER(LOWER(column))", 4, "nested functions should be complex"},
+ }
+
+ for _, tc := range testCases {
+ complexity, err := comparer.GetExpressionComplexity(tc.expr)
+ require.NoError(t, err, "Should calculate complexity for: %s", tc.expr)
+ require.GreaterOrEqual(t, complexity, tc.minComplexity,
+ "CRITICAL BUG: Complexity for %s (%s) should be at least %d, got %d",
+ tc.expr, tc.description, tc.minComplexity, complexity)
+ }
+ })
+}
+
+// TestPostgreSQLExpressionComparer_MemoryAndPerformance tests performance requirements
+func TestPostgreSQLExpressionComparer_MemoryAndPerformance(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ t.Run("memory_efficiency_large_expressions", func(t *testing.T) {
+ // CRITICAL: Should handle large expressions without excessive memory use
+ largeExpr := strings.Repeat("column_name_", 1000) + "final"
+
+ // Should not crash or consume excessive memory
+ result, err := comparer.CompareExpressions(largeExpr, strings.ToUpper(largeExpr))
+ require.NoError(t, err, "Should handle large expressions efficiently")
+ require.True(t, result, "Large expressions should be comparable")
+
+ // Normalization should also work
+ normalized, err := comparer.NormalizeExpression(largeExpr)
+ require.NoError(t, err, "Should normalize large expressions efficiently")
+ require.NotEmpty(t, normalized, "Normalized expression should not be empty")
+ })
+
+ t.Run("performance_consistency", func(t *testing.T) {
+ // CRITICAL: Performance should be consistent across different expression types
+ expressions := []string{
+ "simple",
+ "schema.table.column",
+ "UPPER(column)",
+ "a = b AND c = d OR e = f",
+ "(a + b) * (c - d) / (e + f)",
+ }
+
+ for _, expr := range expressions {
+ // Each expression should complete quickly
+ start := testing.Short()
+ result, err := comparer.CompareExpressions(expr, strings.ToUpper(expr))
+ _ = start // Timing check in real implementation would go here
+
+ require.NoError(t, err, "Expression should not cause performance issues: %s", expr)
+ require.True(t, result, "Expression should be comparable: %s", expr)
+ }
+ })
+}
diff --git a/backend/plugin/schema/pg/ast/expression_normalizer.go b/backend/plugin/schema/pg/ast/expression_normalizer.go
index 7107e4ed26..13c7f85365 100644
--- a/backend/plugin/schema/pg/ast/expression_normalizer.go
+++ b/backend/plugin/schema/pg/ast/expression_normalizer.go
@@ -187,11 +187,27 @@ func (v *normalizationVisitor) normalizeIdentifier(identifier string) string {
return ""
}
- // Handle quoted identifiers - preserve exact case
+ // Handle quoted identifiers
if v.isQuotedIdentifier(identifier) {
+ // Remove quotes and get the actual identifier
+ unquoted := identifier[1 : len(identifier)-1]
+
+ // In PostgreSQL, if a quoted identifier is all lowercase,
+ // it's equivalent to the unquoted version
+ if strings.ToLower(unquoted) == unquoted {
+ // If quoted identifier is all lowercase, normalize as unquoted
+ return v.normalizeUnquotedIdentifier(unquoted)
+ }
+
+ // Otherwise, preserve the quoted form for case-sensitive comparison
return identifier
}
+ return v.normalizeUnquotedIdentifier(identifier)
+}
+
+// normalizeUnquotedIdentifier normalizes unquoted identifiers
+func (v *normalizationVisitor) normalizeUnquotedIdentifier(identifier string) string {
// For unquoted identifiers, apply case normalization
if v.normalizer.CaseSensitive {
return identifier
@@ -201,8 +217,13 @@ func (v *normalizationVisitor) normalizeIdentifier(identifier string) string {
}
// normalizeFunctionName normalizes function names
-func (*normalizationVisitor) normalizeFunctionName(name string) string {
- // Function names are case-insensitive in PostgreSQL
+func (v *normalizationVisitor) normalizeFunctionName(name string) string {
+ // Handle quoted function names - preserve exact case
+ if v.isQuotedIdentifier(name) {
+ return name
+ }
+
+ // Function names are case-insensitive in PostgreSQL for unquoted names
return strings.ToLower(name)
}
@@ -241,27 +262,58 @@ func (*normalizationVisitor) shouldSwapOperands(left, right ExpressionAST) bool
// isSignificantParentheses determines if parentheses are semantically significant
func (*normalizationVisitor) isSignificantParentheses(expr *ParenthesesExpr) bool {
// Parentheses are significant if they change operator precedence or grouping
- // For now, we use a simple heuristic - this could be made more sophisticated
inner := expr.Inner
if inner == nil {
return false
}
- // Parentheses around binary operations might be significant for precedence
- if _, isBinaryOp := inner.(*BinaryOpExpr); isBinaryOp {
- // Could analyze the context to determine if parentheses change precedence
- // For now, be conservative and keep them
- return true
- }
-
- // Parentheses around simple identifiers or literals are usually not significant
+ // Parentheses around simple identifiers or literals are never significant
+ // This is the key insight: (name) and name are always semantically equivalent
switch inner.(type) {
case *IdentifierExpr, *LiteralExpr:
return false
- default:
- return true // be conservative
}
+
+ // Parentheses around binary operations might be significant for precedence
+ if binaryOp, isBinaryOp := inner.(*BinaryOpExpr); isBinaryOp {
+ // For most practical cases in filter expressions, parentheses around
+ // high-precedence operators (=, <>, <, >, etc.) are not significant
+ // when used with lower-precedence operators (AND, OR)
+ op := strings.ToUpper(binaryOp.Operator)
+
+ // High precedence comparison operators usually don't need parentheses
+ highPrecedenceOps := map[string]bool{
+ "=": true,
+ "<>": true,
+ "!=": true,
+ "<": true,
+ ">": true,
+ "<=": true,
+ ">=": true,
+ "LIKE": true,
+ "ILIKE": true,
+ "IS NULL": true,
+ "IS NOT NULL": true,
+ "::": true, // Type cast operator
+ }
+
+ if highPrecedenceOps[op] {
+ return false // These operators have high precedence, parentheses usually not needed
+ }
+
+ // For AND/OR operators, parentheses might be significant for grouping
+ // But in simple cases like (A AND B) vs A AND B, they're not significant
+ if op == "AND" || op == "OR" {
+ return false // Allow AND/OR to be ungrouped for simple cases
+ }
+
+ // Be conservative for other operators
+ return true
+ }
+
+ // Be conservative for other expression types (functions, etc.)
+ return true
}
// isQuotedIdentifier checks if an identifier is quoted
diff --git a/backend/plugin/schema/pg/ast/expression_parser.go b/backend/plugin/schema/pg/ast/expression_parser.go
index 6513394fb8..e954bf3ac3 100644
--- a/backend/plugin/schema/pg/ast/expression_parser.go
+++ b/backend/plugin/schema/pg/ast/expression_parser.go
@@ -68,10 +68,11 @@ func (p *ExpressionParser) parseExpressionTokens(tokens []antlr.Token, start, en
return nil, nil
}
- // Handle parentheses
+ // Handle parentheses - only if they truly wrap the entire expression
if tokens[start].GetText() == "(" && tokens[end-1].GetText() == ")" {
- // Check if parentheses are balanced and wrap the entire expression
- if p.isBalancedParentheses(tokens, start, end) {
+ // Check if the opening parenthesis has a matching closing parenthesis at the end
+ // AND there are no other top-level operators outside these parentheses
+ if p.isBalancedParentheses(tokens, start, end) && p.parenthesesWrapEntireExpression(tokens, start, end) {
inner, err := p.parseExpressionTokens(tokens, start+1, end-1)
if err != nil {
return nil, err
@@ -80,6 +81,12 @@ func (p *ExpressionParser) parseExpressionTokens(tokens []antlr.Token, start, en
}
}
+ // Check for expression lists (comma-separated expressions)
+ // Only parse as list if there are actually commas at the top level
+ if listExpr := p.parseExpressionList(tokens, start, end); listExpr != nil {
+ return listExpr, nil
+ }
+
// Find binary operators (precedence handling)
if binaryExpr := p.parseBinaryOperation(tokens, start, end); binaryExpr != nil {
return binaryExpr, nil
@@ -116,15 +123,311 @@ func (p *ExpressionParser) parseExpressionTokens(tokens []antlr.Token, start, en
}, nil
}
+// parseMultiKeywordOperators parses multi-keyword operators like IS NULL, BETWEEN...AND, etc.
+func (p *ExpressionParser) parseMultiKeywordOperators(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Look for CASE expressions first (they are most complex)
+ if caseExpr := p.parseCaseExpression(tokens, start, end); caseExpr != nil {
+ return caseExpr
+ }
+
+ // Look for IS NULL / IS NOT NULL patterns
+ if nullExpr := p.parseIsNullOperator(tokens, start, end); nullExpr != nil {
+ return nullExpr
+ }
+
+ // Look for BETWEEN...AND patterns
+ return p.parseBetweenOperator(tokens, start, end)
+}
+
+// parseCaseExpression parses CASE WHEN...THEN...ELSE...END expressions
+func (p *ExpressionParser) parseCaseExpression(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Look for CASE...END pattern
+ if start < end && strings.ToUpper(tokens[start].GetText()) == "CASE" &&
+ strings.ToUpper(tokens[end-1].GetText()) == "END" {
+ // Parse the CASE expression content between CASE and END
+ var caseArgs []ExpressionAST
+
+ // Add a marker to identify this as a CASE expression
+ caseArgs = append(caseArgs, &LiteralExpr{Value: "CASE", ValueType: "keyword"})
+
+ // Parse WHEN...THEN pairs and optional ELSE
+ i := start + 1
+ for i < end-1 {
+ tokenText := strings.ToUpper(tokens[i].GetText())
+
+ if tokenText == "WHEN" {
+ // Find the corresponding THEN
+ thenPos := -1
+ parenLevel := 0
+ for j := i + 1; j < end-1; j++ {
+ if tokens[j].GetText() == "(" {
+ parenLevel++
+ } else if tokens[j].GetText() == ")" {
+ parenLevel--
+ } else if parenLevel == 0 && strings.ToUpper(tokens[j].GetText()) == "THEN" {
+ thenPos = j
+ break
+ }
+ }
+
+ if thenPos != -1 {
+ // Parse condition between WHEN and THEN
+ condition, _ := p.parseExpressionTokens(tokens, i+1, thenPos)
+ if condition != nil {
+ caseArgs = append(caseArgs, condition)
+ }
+
+ // Find the next WHEN, ELSE, or END to determine the THEN value range
+ nextPos := end - 1 // default to END
+ parenLevel = 0
+ for j := thenPos + 1; j < end-1; j++ {
+ if tokens[j].GetText() == "(" {
+ parenLevel++
+ } else if tokens[j].GetText() == ")" {
+ parenLevel--
+ } else if parenLevel == 0 {
+ nextToken := strings.ToUpper(tokens[j].GetText())
+ if nextToken == "WHEN" || nextToken == "ELSE" {
+ nextPos = j
+ break
+ }
+ }
+ }
+
+ // Parse value between THEN and next keyword
+ value, _ := p.parseExpressionTokens(tokens, thenPos+1, nextPos)
+ if value != nil {
+ caseArgs = append(caseArgs, value)
+ }
+
+ i = nextPos
+ } else {
+ i++
+ }
+ } else if tokenText == "ELSE" {
+ // Parse ELSE value (everything from ELSE to END)
+ elseValue, _ := p.parseExpressionTokens(tokens, i+1, end-1)
+ if elseValue != nil {
+ caseArgs = append(caseArgs, elseValue)
+ }
+ break
+ } else {
+ i++
+ }
+ }
+
+ return &FunctionExpr{
+ Name: "CASE",
+ Args: caseArgs,
+ }
+ }
+
+ return nil
+}
+
+// parseIsNullOperator parses IS NULL and IS NOT NULL operators
+func (p *ExpressionParser) parseIsNullOperator(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Look for IS NULL pattern (minimum 3 tokens: operand IS NULL)
+ for i := start + 1; i < end-1; i++ {
+ if p.getParenthesesLevel(tokens, start, i) == 0 {
+ isToken := strings.ToUpper(tokens[i].GetText())
+
+ if isToken == "IS" {
+ // Check for IS NOT NULL (4 tokens after IS)
+ if i+2 < end {
+ notToken := strings.ToUpper(tokens[i+1].GetText())
+ nullToken := strings.ToUpper(tokens[i+2].GetText())
+
+ if notToken == "NOT" && nullToken == "NULL" {
+ // Parse: operand IS NOT NULL
+ left, _ := p.parseExpressionTokens(tokens, start, i)
+ if left != nil {
+ return &BinaryOpExpr{
+ Left: left,
+ Operator: "IS NOT NULL",
+ Right: &LiteralExpr{Value: "NULL", ValueType: "null"},
+ }
+ }
+ }
+ }
+
+ // Check for IS NULL (2 tokens after IS)
+ if i+1 < end {
+ nullToken := strings.ToUpper(tokens[i+1].GetText())
+
+ if nullToken == "NULL" {
+ // Parse: operand IS NULL
+ left, _ := p.parseExpressionTokens(tokens, start, i)
+ if left != nil {
+ return &BinaryOpExpr{
+ Left: left,
+ Operator: "IS NULL",
+ Right: &LiteralExpr{Value: "NULL", ValueType: "null"},
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+// parseBetweenOperator parses BETWEEN...AND operators
+func (p *ExpressionParser) parseBetweenOperator(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Look for BETWEEN pattern (minimum 5 tokens: operand BETWEEN value1 AND value2)
+ for i := start + 1; i < end-3; i++ {
+ if p.getParenthesesLevel(tokens, start, i) == 0 {
+ betweenToken := strings.ToUpper(tokens[i].GetText())
+
+ if betweenToken == "BETWEEN" {
+ // Find the AND keyword
+ for j := i + 2; j < end-1; j++ {
+ if p.getParenthesesLevel(tokens, i+1, j) == 0 {
+ andToken := strings.ToUpper(tokens[j].GetText())
+
+ if andToken == "AND" {
+ // Parse: operand BETWEEN value1 AND value2
+ left, _ := p.parseExpressionTokens(tokens, start, i)
+ value1, _ := p.parseExpressionTokens(tokens, i+1, j)
+ value2, _ := p.parseExpressionTokens(tokens, j+1, end)
+
+ if left != nil && value1 != nil && value2 != nil {
+ // Create a special function-like expression for BETWEEN
+ return &FunctionExpr{
+ Name: "BETWEEN",
+ Args: []ExpressionAST{left, value1, value2},
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+// parseExpressionList parses comma-separated expression lists
+func (p *ExpressionParser) parseExpressionList(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Look for comma separators at the top level (not inside parentheses)
+ var commaPositions []int
+ parenLevel := 0
+
+ for i := start; i < end; i++ {
+ tokenText := tokens[i].GetText()
+ if tokenText == "(" {
+ parenLevel++
+ } else if tokenText == ")" {
+ parenLevel--
+ } else if tokenText == "," && parenLevel == 0 {
+ commaPositions = append(commaPositions, i)
+ }
+ }
+
+ // If we found commas at the top level, parse as expression list
+ if len(commaPositions) > 0 {
+ var elements []ExpressionAST
+
+ // Parse elements between commas, but use a non-recursive approach for list elements
+ prevPos := start
+ for _, commaPos := range commaPositions {
+ if commaPos > prevPos {
+ element := p.parseNonListExpression(tokens, prevPos, commaPos)
+ if element != nil {
+ elements = append(elements, element)
+ }
+ }
+ prevPos = commaPos + 1
+ }
+
+ // Parse last element
+ if prevPos < end {
+ element := p.parseNonListExpression(tokens, prevPos, end)
+ if element != nil {
+ elements = append(elements, element)
+ }
+ }
+
+ if len(elements) > 1 {
+ return &ListExpr{Elements: elements}
+ }
+ }
+
+ return nil
+}
+
+// parseNonListExpression parses expressions but excludes list parsing to avoid infinite recursion
+func (p *ExpressionParser) parseNonListExpression(tokens []antlr.Token, start, end int) ExpressionAST {
+ if start >= end {
+ return nil
+ }
+
+ // Handle parentheses
+ if tokens[start].GetText() == "(" && tokens[end-1].GetText() == ")" {
+ // Check if parentheses are balanced and wrap the entire expression
+ if p.isBalancedParentheses(tokens, start, end) {
+ inner := p.parseNonListExpression(tokens, start+1, end-1)
+ if inner != nil {
+ return &ParenthesesExpr{Inner: inner}
+ }
+ }
+ }
+
+ // Find binary operators (precedence handling)
+ if binaryExpr := p.parseBinaryOperation(tokens, start, end); binaryExpr != nil {
+ return binaryExpr
+ }
+
+ // Find unary operators
+ if unaryExpr := p.parseUnaryOperation(tokens, start, end); unaryExpr != nil {
+ return unaryExpr
+ }
+
+ // Parse function calls
+ if funcExpr := p.parseFunctionCall(tokens, start, end); funcExpr != nil {
+ return funcExpr
+ }
+
+ // Parse single token (identifier or literal)
+ if end-start == 1 {
+ result, _ := p.parseSingleToken(tokens[start])
+ return result
+ }
+
+ // Parse qualified identifier (schema.table.column)
+ if qualifiedExpr := p.parseQualifiedIdentifier(tokens, start, end); qualifiedExpr != nil {
+ return qualifiedExpr
+ }
+
+ // Fallback: create a literal expression with the concatenated text
+ var parts []string
+ for i := start; i < end; i++ {
+ parts = append(parts, tokens[i].GetText())
+ }
+ return &LiteralExpr{
+ Value: strings.Join(parts, " "),
+ ValueType: "unknown",
+ }
+}
+
// parseBinaryOperation parses binary operations with precedence
func (p *ExpressionParser) parseBinaryOperation(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Check for multi-keyword operators first
+ if multiKeywordExpr := p.parseMultiKeywordOperators(tokens, start, end); multiKeywordExpr != nil {
+ return multiKeywordExpr
+ }
+
// Precedence levels (lowest to highest)
precedenceLevels := [][]string{
{"OR", "||"}, // lowest precedence
{"AND", "&&"},
{"=", "<>", "!=", "<", ">", "<=", ">=", "LIKE", "ILIKE"},
{"+", "-"},
- {"*", "/", "%"}, // highest precedence
+ {"*", "/", "%"},
+ {"::"}, // type cast has high precedence
}
// Find operators from lowest to highest precedence
@@ -176,6 +479,11 @@ func (p *ExpressionParser) parseUnaryOperation(tokens []antlr.Token, start, end
// parseFunctionCall parses function calls
func (p *ExpressionParser) parseFunctionCall(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Check for special EXTRACT function first
+ if extractExpr := p.parseExtractFunction(tokens, start, end); extractExpr != nil {
+ return extractExpr
+ }
+
// Look for pattern: identifier ( args )
for i := start; i < end-1; i++ {
if tokens[i+1].GetText() == "(" {
@@ -216,6 +524,49 @@ func (p *ExpressionParser) parseFunctionCall(tokens []antlr.Token, start, end in
return nil
}
+// parseExtractFunction parses EXTRACT(field FROM source) function calls
+func (p *ExpressionParser) parseExtractFunction(tokens []antlr.Token, start, end int) ExpressionAST {
+ // Look for EXTRACT( pattern
+ if start < end-1 &&
+ strings.ToUpper(tokens[start].GetText()) == "EXTRACT" &&
+ tokens[start+1].GetText() == "(" {
+ // Find matching closing parenthesis
+ parenLevel := 0
+ closeParenPos := -1
+ for j := start + 1; j < end; j++ {
+ if tokens[j].GetText() == "(" {
+ parenLevel++
+ } else if tokens[j].GetText() == ")" {
+ parenLevel--
+ if parenLevel == 0 {
+ closeParenPos = j
+ break
+ }
+ }
+ }
+
+ if closeParenPos == end-1 { // EXTRACT call spans the entire range
+ // Look for FROM keyword inside parentheses
+ for k := start + 2; k < closeParenPos-1; k++ {
+ if strings.ToUpper(tokens[k].GetText()) == "FROM" {
+ // Parse: EXTRACT(field FROM source)
+ field, _ := p.parseExpressionTokens(tokens, start+2, k)
+ source, _ := p.parseExpressionTokens(tokens, k+1, closeParenPos)
+
+ if field != nil && source != nil {
+ return &FunctionExpr{
+ Name: "EXTRACT",
+ Args: []ExpressionAST{field, source},
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
// parseQualifiedIdentifier parses qualified identifiers like schema.table.column
func (p *ExpressionParser) parseQualifiedIdentifier(tokens []antlr.Token, start, end int) ExpressionAST {
if end-start < 1 {
@@ -269,6 +620,11 @@ func (p *ExpressionParser) parseQualifiedIdentifier(tokens []antlr.Token, start,
func (p *ExpressionParser) parseSingleToken(token antlr.Token) (ExpressionAST, error) {
tokenText := token.GetText()
+ // Check if it's a quoted identifier (PostgreSQL uses double quotes for identifiers)
+ if p.isQuotedIdentifier(tokenText) {
+ return &IdentifierExpr{Name: tokenText}, nil
+ }
+
// Check if it's a literal
if p.isStringLiteral(tokenText) {
return &LiteralExpr{
@@ -358,6 +714,32 @@ func (*ExpressionParser) isBalancedParentheses(tokens []antlr.Token, start, end
return level == 0
}
+// parenthesesWrapEntireExpression checks if parentheses at start/end truly wrap the entire expression
+func (*ExpressionParser) parenthesesWrapEntireExpression(tokens []antlr.Token, start, end int) bool {
+ if start >= end-1 || tokens[start].GetText() != "(" || tokens[end-1].GetText() != ")" {
+ return false
+ }
+
+ // Find the matching closing parenthesis for the opening parenthesis at start
+ level := 0
+ matchingClosePos := -1
+
+ for i := start; i < end; i++ {
+ if tokens[i].GetText() == "(" {
+ level++
+ } else if tokens[i].GetText() == ")" {
+ level--
+ if level == 0 {
+ matchingClosePos = i
+ break
+ }
+ }
+ }
+
+ // If the matching closing parenthesis is at the end, then parentheses wrap entire expression
+ return matchingClosePos == end-1
+}
+
// isIdentifierToken checks if token is an identifier
func (*ExpressionParser) isIdentifierToken(token antlr.Token) bool {
tokenText := token.GetText()
@@ -382,11 +764,16 @@ func (*ExpressionParser) isIdentifierToken(token antlr.Token) bool {
return false
}
-// isStringLiteral checks if token is a string literal
+// isStringLiteral checks if token is a string literal (single quotes in PostgreSQL)
func (*ExpressionParser) isStringLiteral(tokenText string) bool {
return len(tokenText) >= 2 &&
- ((tokenText[0] == '\'' && tokenText[len(tokenText)-1] == '\'') ||
- (tokenText[0] == '"' && tokenText[len(tokenText)-1] == '"'))
+ tokenText[0] == '\'' && tokenText[len(tokenText)-1] == '\''
+}
+
+// isQuotedIdentifier checks if token is a quoted identifier (double quotes in PostgreSQL)
+func (*ExpressionParser) isQuotedIdentifier(tokenText string) bool {
+ return len(tokenText) >= 2 &&
+ tokenText[0] == '"' && tokenText[len(tokenText)-1] == '"'
}
// isNumericLiteral checks if token is numeric
diff --git a/backend/plugin/schema/pg/ast/expression_parser_parentheses_test.go b/backend/plugin/schema/pg/ast/expression_parser_parentheses_test.go
new file mode 100644
index 0000000000..95b8e383fb
--- /dev/null
+++ b/backend/plugin/schema/pg/ast/expression_parser_parentheses_test.go
@@ -0,0 +1,457 @@
+package ast
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/antlr4-go/antlr/v4"
+ pgparser "github.com/bytebase/parser/postgresql"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// TestParenthesesMatching tests comprehensive parentheses matching scenarios
+func TestParenthesesMatching(t *testing.T) {
+ testCases := []struct {
+ name string
+ expression string
+ expectParseSuccess bool
+ expectParentheses bool
+ expectedStructure string
+ description string
+ }{
+ {
+ name: "simple_parentheses",
+ expression: "(a)",
+ expectParseSuccess: true,
+ expectParentheses: true,
+ expectedStructure: "Parentheses(Identifier)",
+ description: "Simple parentheses around identifier",
+ },
+ {
+ name: "nested_parentheses",
+ expression: "((a))",
+ expectParseSuccess: true,
+ expectParentheses: true,
+ expectedStructure: "Parentheses(Parentheses(Identifier))",
+ description: "Nested parentheses",
+ },
+ {
+ name: "function_with_parentheses_arg",
+ expression: "func((a))",
+ expectParseSuccess: true,
+ expectParentheses: false, // outer structure should be function
+ expectedStructure: "Function(Parentheses(Identifier))",
+ description: "Function call with parenthesized argument",
+ },
+ {
+ name: "binary_op_with_parentheses",
+ expression: "(a) + (b)",
+ expectParseSuccess: true,
+ expectParentheses: false, // outer structure should be binary op
+ expectedStructure: "BinaryOp(Parentheses(Identifier), Parentheses(Identifier))",
+ description: "Binary operation with parenthesized operands",
+ },
+ {
+ name: "unmatched_open_paren",
+ expression: "(a",
+ expectParseSuccess: true, // should fallback to literal
+ expectParentheses: false,
+ expectedStructure: "Literal",
+ description: "Unmatched opening parenthesis",
+ },
+ {
+ name: "unmatched_close_paren",
+ expression: "a)",
+ expectParseSuccess: true, // should fallback to literal
+ expectParentheses: false,
+ expectedStructure: "Literal",
+ description: "Unmatched closing parenthesis",
+ },
+ {
+ name: "mismatched_parentheses",
+ expression: "(a))(b",
+ expectParseSuccess: true, // should fallback to literal
+ expectParentheses: false,
+ expectedStructure: "Literal",
+ description: "Mismatched parentheses pattern",
+ },
+ {
+ name: "empty_parentheses",
+ expression: "()",
+ expectParseSuccess: true,
+ expectParentheses: true,
+ expectedStructure: "Parentheses(null)",
+ description: "Empty parentheses",
+ },
+ {
+ name: "complex_nested_expression",
+ expression: "((a + b) * (c - d))",
+ expectParseSuccess: true,
+ expectParentheses: true,
+ expectedStructure: "Parentheses(BinaryOp(Parentheses(BinaryOp), Parentheses(BinaryOp)))",
+ description: "Complex nested expression with multiple parentheses levels",
+ },
+ {
+ name: "partial_wrapping_parentheses",
+ expression: "(a + b) * c",
+ expectParseSuccess: true,
+ expectParentheses: false, // outer should be binary op, not parentheses
+ expectedStructure: "BinaryOp(Parentheses(BinaryOp), Identifier)",
+ description: "Parentheses that don't wrap entire expression",
+ },
+ }
+
+ parser := NewExpressionParser()
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Parse the expression
+ ast, err := parser.ParseExpression(tc.expression)
+
+ if tc.expectParseSuccess {
+ require.NoError(t, err, "Expected successful parsing for: %s", tc.description)
+ require.NotNil(t, ast, "Expected non-nil AST for: %s", tc.description)
+
+ // Check if the top-level structure matches expectation
+ if tc.expectParentheses {
+ _, isParens := ast.(*ParenthesesExpr)
+ assert.True(t, isParens, "Expected parentheses expression for: %s, got: %T", tc.description, ast)
+ }
+
+ // Print actual structure for debugging
+ t.Logf("Expression: %s", tc.expression)
+ t.Logf("Expected: %s", tc.expectedStructure)
+ t.Logf("Actual AST: %s", ast.String())
+ t.Logf("Actual structure: %s", describeAST(ast))
+ } else {
+ assert.Error(t, err, "Expected parsing error for: %s", tc.description)
+ }
+ })
+ }
+}
+
+// TestParenthesesMatchingHelpers tests the individual helper functions
+func TestParenthesesMatchingHelpers(t *testing.T) {
+ parser := NewExpressionParser()
+
+ testCases := []struct {
+ name string
+ expression string
+ expectedBalance bool
+ expectedWrap bool
+ description string
+ }{
+ {
+ name: "simple_balanced",
+ expression: "(a)",
+ expectedBalance: true,
+ expectedWrap: true,
+ description: "Simple balanced parentheses",
+ },
+ {
+ name: "nested_balanced",
+ expression: "((a))",
+ expectedBalance: true,
+ expectedWrap: true,
+ description: "Nested balanced parentheses",
+ },
+ {
+ name: "unbalanced_open",
+ expression: "(a",
+ expectedBalance: false,
+ expectedWrap: false,
+ description: "Unbalanced - missing close",
+ },
+ {
+ name: "unbalanced_close",
+ expression: "a)",
+ expectedBalance: false,
+ expectedWrap: false,
+ description: "Unbalanced - extra close",
+ },
+ {
+ name: "partial_wrap",
+ expression: "(a) + b",
+ expectedBalance: true,
+ expectedWrap: false,
+ description: "Balanced but doesn't wrap entire expression",
+ },
+ {
+ name: "empty_parens",
+ expression: "()",
+ expectedBalance: true,
+ expectedWrap: true,
+ description: "Empty parentheses",
+ },
+ {
+ name: "nested_with_extra_content",
+ expression: "((a + b)) + c)",
+ expectedBalance: false,
+ expectedWrap: false,
+ description: "Nested parentheses with extra content - should not wrap entire expression",
+ },
+ {
+ name: "proper_nested_wrapping",
+ expression: "((a + b) + c)",
+ expectedBalance: true,
+ expectedWrap: true,
+ description: "Proper nested parentheses that wrap entire expression",
+ },
+ {
+ name: "edge_case_with_whitespace",
+ expression: "(a + b) )",
+ expectedBalance: false,
+ expectedWrap: false,
+ description: "Edge case with whitespace and extra parenthesis",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ tokens := tokenizeExpression(tc.expression)
+ start := 0
+ end := len(tokens)
+
+ // Test isBalancedParentheses
+ actualBalance := parser.isBalancedParentheses(tokens, start, end)
+ assert.Equal(t, tc.expectedBalance, actualBalance,
+ "isBalancedParentheses mismatch for: %s", tc.description)
+
+ // Test parenthesesWrapEntireExpression (only if starts and ends with parentheses)
+ if len(tokens) >= 2 && tokens[0].GetText() == "(" && tokens[end-1].GetText() == ")" {
+ actualWrap := parser.parenthesesWrapEntireExpression(tokens, start, end)
+ assert.Equal(t, tc.expectedWrap, actualWrap,
+ "parenthesesWrapEntireExpression mismatch for: %s", tc.description)
+ }
+ })
+ }
+}
+
+// TestParenthesesLevelCalculation tests the getParenthesesLevel function
+func TestParenthesesLevelCalculation(t *testing.T) {
+ parser := NewExpressionParser()
+
+ testCases := []struct {
+ expression string
+ pos int
+ expectedLevel int
+ description string
+ }{
+ {
+ expression: "(a + b)",
+ pos: 1, // at 'a'
+ expectedLevel: 1,
+ description: "Level 1 inside simple parentheses",
+ },
+ {
+ expression: "((a) + (b))",
+ pos: 2, // at 'a'
+ expectedLevel: 2,
+ description: "Level 2 inside nested parentheses",
+ },
+ {
+ expression: "(a) + (b)",
+ pos: 4, // at '+'
+ expectedLevel: 0,
+ description: "Level 0 between parentheses groups",
+ },
+ {
+ expression: "func((a + b), c)",
+ pos: 4, // at '+'
+ expectedLevel: 2,
+ description: "Level 2 inside function call with nested parentheses",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.description, func(t *testing.T) {
+ tokens := tokenizeExpression(tc.expression)
+ require.True(t, tc.pos < len(tokens), "Position out of bounds")
+
+ actualLevel := parser.getParenthesesLevel(tokens, 0, tc.pos)
+ assert.Equal(t, tc.expectedLevel, actualLevel,
+ "Parentheses level mismatch at position %d in expression: %s", tc.pos, tc.expression)
+ })
+ }
+}
+
+// TestEdgeCasesAndErrorHandling tests edge cases and error conditions
+func TestEdgeCasesAndErrorHandling(t *testing.T) {
+ parser := NewExpressionParser()
+
+ edgeCases := []struct {
+ name string
+ expression string
+ expectError bool
+ description string
+ }{
+ {
+ name: "deeply_nested",
+ expression: "(((((a)))))",
+ expectError: false,
+ description: "Deeply nested parentheses",
+ },
+ {
+ name: "alternating_parens",
+ expression: "(a)(b)(c)",
+ expectError: false,
+ description: "Multiple separate parentheses groups",
+ },
+ {
+ name: "complex_unbalanced",
+ expression: "((a + (b * c)) + d))",
+ expectError: false, // should parse as literal
+ description: "Complex expression with extra closing paren",
+ },
+ {
+ name: "mixed_brackets",
+ expression: "(a + [b])",
+ expectError: false,
+ description: "Mixed parentheses and brackets",
+ },
+ }
+
+ for _, tc := range edgeCases {
+ t.Run(tc.name, func(t *testing.T) {
+ ast, err := parser.ParseExpression(tc.expression)
+
+ if tc.expectError {
+ assert.Error(t, err, "Expected error for: %s", tc.description)
+ } else {
+ assert.NoError(t, err, "Unexpected error for: %s", tc.description)
+ assert.NotNil(t, ast, "Expected non-nil AST for: %s", tc.description)
+ t.Logf("Expression: %s -> %s", tc.expression, ast.String())
+ }
+ })
+ }
+}
+
+// Helper functions
+
+// tokenizeExpression converts an expression string to tokens for testing
+func tokenizeExpression(expr string) []antlr.Token {
+ inputStream := antlr.NewInputStream(expr)
+ lexer := pgparser.NewPostgreSQLLexer(inputStream)
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+ stream.Fill()
+ tokens := stream.GetAllTokens()
+
+ // Filter out whitespace and EOF tokens
+ var filteredTokens []antlr.Token
+ for _, token := range tokens {
+ if token.GetText() != "<EOF>" && token.GetChannel() == antlr.TokenDefaultChannel {
+ filteredTokens = append(filteredTokens, token)
+ }
+ }
+ return filteredTokens
+}
+
+// describeAST provides a structural description of an AST for testing
+func describeAST(expr ExpressionAST) string {
+ if expr == nil {
+ return "null"
+ }
+
+ switch e := expr.(type) {
+ case *ParenthesesExpr:
+ return fmt.Sprintf("Parentheses(%s)", describeAST(e.Inner))
+ case *FunctionExpr:
+ var args []string
+ for _, arg := range e.Args {
+ args = append(args, describeAST(arg))
+ }
+ if len(args) == 0 {
+ return fmt.Sprintf("Function(%s)", e.Name)
+ }
+ return fmt.Sprintf("Function(%s, %v)", e.Name, args)
+ case *BinaryOpExpr:
+ return fmt.Sprintf("BinaryOp(%s, %s)", describeAST(e.Left), describeAST(e.Right))
+ case *UnaryOpExpr:
+ return fmt.Sprintf("UnaryOp(%s, %s)", e.Operator, describeAST(e.Operand))
+ case *IdentifierExpr:
+ return "Identifier"
+ case *LiteralExpr:
+ return "Literal"
+ case *ListExpr:
+ return fmt.Sprintf("List(%d)", len(e.Elements))
+ default:
+ return fmt.Sprintf("Unknown(%T)", expr)
+ }
+}
+
+// TestGitHubCommentIssues tests specific issues mentioned in GitHub PR comments
+func TestGitHubCommentIssues(t *testing.T) {
+ comparer := NewPostgreSQLExpressionComparer()
+
+ testCases := []struct {
+ name string
+ expr1 string
+ expr2 string
+ shouldEqual bool
+ description string
+ }{
+ {
+ name: "AND_OR_precedence_parentheses_significant",
+ expr1: "(A AND B) OR C",
+ expr2: "A AND (B OR C)",
+ shouldEqual: false,
+ description: "Parentheses around AND/OR should be significant for precedence: (A AND B) OR C ≠ A AND (B OR C)",
+ },
+ {
+ name: "AND_OR_same_precedence_equivalent",
+ expr1: "(A AND B) AND C",
+ expr2: "A AND B AND C",
+ shouldEqual: true,
+ description: "Parentheses around same precedence operations should not be significant",
+ },
+ {
+ name: "nested_parentheses_with_extra_content",
+ expr1: "((a + b)) + c)",
+ expr2: "(a + b) + c",
+ shouldEqual: false,
+ description: "Expression with unmatched parentheses should not equal properly formed expression",
+ },
+ {
+ name: "OR_operator_equivalence",
+ expr1: "A || B",
+ expr2: "A OR B",
+ shouldEqual: true,
+ description: "|| and OR operators should be equivalent",
+ },
+ {
+ name: "complex_precedence_case",
+ expr1: "A AND (B OR C) AND D",
+ expr2: "(A AND (B OR C)) AND D",
+ shouldEqual: true,
+ description: "Parentheses that don't change precedence should be ignored",
+ },
+ {
+ name: "test_failure_case",
+ expr1: "A + B",
+ expr2: "C + D",
+ shouldEqual: false,
+ description: "Completely different expressions should not be equal",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ result, err := comparer.CompareExpressions(tc.expr1, tc.expr2)
+ require.NoError(t, err, "Comparison should not fail for: %s", tc.description)
+
+ if tc.shouldEqual {
+ assert.True(t, result, "Expected expressions to be equal: %s vs %s (%s)",
+ tc.expr1, tc.expr2, tc.description)
+ } else {
+ assert.False(t, result, "Expected expressions to be different: %s vs %s (%s)",
+ tc.expr1, tc.expr2, tc.description)
+ }
+
+ // Also test in reverse order to ensure symmetry
+ reverseResult, err := comparer.CompareExpressions(tc.expr2, tc.expr1)
+ require.NoError(t, err, "Reverse comparison should not fail")
+ assert.Equal(t, result, reverseResult, "Comparison should be symmetric")
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/ast/expression_visitor.go b/backend/plugin/schema/pg/ast/expression_visitor.go
index fdd6f7aa38..13589b5d85 100644
--- a/backend/plugin/schema/pg/ast/expression_visitor.go
+++ b/backend/plugin/schema/pg/ast/expression_visitor.go
@@ -437,7 +437,8 @@ func (*ExpressionValidatorVisitor) isValidBinaryOperator(operator string) bool {
"=", "<>", "!=", "<", ">", "<=", ">=",
"+", "-", "*", "/", "%",
"AND", "OR", "LIKE", "ILIKE", "IN", "NOT IN",
- "||", // string concatenation or logical OR
+ "||", // string concatenation or logical OR
+ "IS NULL", "IS NOT NULL", // NULL checking operators
}
upper := strings.ToUpper(operator)
diff --git a/backend/plugin/schema/pg/get_database_metadata.go b/backend/plugin/schema/pg/get_database_metadata.go
index 2d4d23d405..2ae8d68eda 100644
--- a/backend/plugin/schema/pg/get_database_metadata.go
+++ b/backend/plugin/schema/pg/get_database_metadata.go
@@ -796,7 +796,7 @@ func (e *metadataExtractor) extractColumnConstraint(ctx parser.IColconstraintele
// Extract the check expression
if expr := ctx.A_expr(); expr != nil {
rawExpression := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(expr)
- check.Expression = e.normalizePostgreSQLCheckExpression(rawExpression)
+ check.Expression = strings.TrimSpace(rawExpression)
}
// Add to table's check constraints
@@ -912,7 +912,7 @@ func (e *metadataExtractor) extractTableConstraint(ctx parser.ITableconstraintCo
}
if expr := constraintElem.A_expr(); expr != nil {
rawExpression := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(expr)
- check.Expression = e.normalizePostgreSQLCheckExpression(rawExpression)
+ check.Expression = strings.TrimSpace(rawExpression)
}
if table.CheckConstraints == nil {
table.CheckConstraints = []*storepb.CheckConstraintMetadata{}
@@ -1938,13 +1938,11 @@ func (e *metadataExtractor) generateIndexDefinition(ctx *parser.IndexstmtContext
if len(index.Expressions) > 0 {
columnList := make([]string, len(index.Expressions))
for i, expr := range index.Expressions {
- // Normalize expression to match PostgreSQL system catalog format
- normalizedExpr := e.normalizePostgreSQLIndexExpression(expr)
// Add DESC if needed
if i < len(index.Descending) && index.Descending[i] {
- columnList[i] = fmt.Sprintf("%s DESC", normalizedExpr)
+ columnList[i] = fmt.Sprintf("%s DESC", expr)
} else {
- columnList[i] = normalizedExpr
+ columnList[i] = expr
}
}
parts = append(parts, fmt.Sprintf("(%s)", strings.Join(columnList, ", ")))
@@ -1959,16 +1957,10 @@ func (e *metadataExtractor) generateIndexDefinition(ctx *parser.IndexstmtContext
// Check for WHERE clause (partial index)
if ctx.Where_clause() != nil {
whereClause := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Where_clause())
- // Normalize WHERE clause to match PostgreSQL system catalog format
+ // Add WHERE clause as-is
if whereClause != "" {
- // Extract the condition part after "WHERE "
- if condition, found := strings.CutPrefix(whereClause, "WHERE "); found {
- // Apply PostgreSQL-style normalization with double parentheses
- normalizedCondition := e.normalizePostgreSQLWhereClause(condition)
- whereClause = fmt.Sprintf("WHERE (%s)", normalizedCondition)
- }
+ parts = append(parts, whereClause)
}
- parts = append(parts, whereClause)
}
// End with semicolon
@@ -2018,38 +2010,6 @@ func (*metadataExtractor) extractIncludeClause(statement string) string {
return strings.TrimSpace(includeClause)
}
-// normalizePostgreSQLWhereClause normalizes WHERE clause conditions to match PostgreSQL system catalog format
-func (*metadataExtractor) normalizePostgreSQLWhereClause(condition string) string {
- // PostgreSQL tends to add parentheses around individual conditions in AND/OR expressions
- // Convert "price > 100.00 AND array_length(category_tags, 1) > 0"
- // to "(price > 100.00) AND (array_length(category_tags, 1) > 0)"
-
- condition = strings.TrimSpace(condition)
-
- // Simple approach: if we have AND/OR operators, add parentheses around each part
- lowerCondition := strings.ToLower(condition)
-
- if strings.Contains(lowerCondition, " and ") || strings.Contains(lowerCondition, " or ") {
- // For this specific case, we can handle the common pattern
- // This is a simplified implementation - a full parser would be more robust
- result := condition
-
- // Replace AND with ) AND ( to separate conditions
- result = strings.ReplaceAll(result, " AND ", ") AND (")
- result = strings.ReplaceAll(result, " and ", ") AND (")
- result = strings.ReplaceAll(result, " OR ", ") OR (")
- result = strings.ReplaceAll(result, " or ", ") OR (")
-
- // Add outer parentheses
- result = "(" + result + ")"
-
- return result
- }
-
- // If no AND/OR operators, return as is
- return condition
-}
-
// generateConstraintIndexDefinition generates the CREATE INDEX definition for constraint-based indexes
func (*metadataExtractor) generateConstraintIndexDefinition(index *storepb.IndexMetadata, tableName, schemaName string) string {
var parts []string
@@ -2305,82 +2265,15 @@ func (*metadataExtractor) normalizeDefaultValue(rawDefault string, column *store
return rawDefault
}
-// extractFunctionExpression semantically extracts function expressions using AST-based comparison to match PostgreSQL's internal representation.
-func (e *metadataExtractor) extractFunctionExpression(ctx *parser.IndexstmtContext, funcExpr parser.IFunc_expr_windowlessContext) string {
+// extractFunctionExpression extracts function expressions preserving the original user input.
+func (*metadataExtractor) extractFunctionExpression(ctx *parser.IndexstmtContext, funcExpr parser.IFunc_expr_windowlessContext) string {
if funcExpr == nil {
return ""
}
- // Get the original text
- originalText := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(funcExpr)
-
- // Use AST-based semantic comparison for standardization
- if e.expressionComparer != nil {
- standardized, err := e.expressionComparer.NormalizeExpression(originalText)
- if err == nil {
- return standardized
- }
- // If standardization fails, log the error but continue with original text
- // In a production system, we might want to log this for debugging
- }
-
- // Fallback to original text if AST standardization fails
- return originalText
-}
-
-// normalizePostgreSQLIndexExpression normalizes index expressions to match PostgreSQL system catalog format
-func (*metadataExtractor) normalizePostgreSQLIndexExpression(expression string) string {
- // PostgreSQL normalizes expressions in the system catalog:
- // 1. Removes spaces around :: cast operator
- // 2. Adds parentheses around column names in function calls
- // Example: "lower(name :: text)" becomes "lower((name)::text)"
-
- expression = strings.TrimSpace(expression)
-
- // Handle cast operators - remove spaces around ::
- expression = strings.ReplaceAll(expression, " :: ", "::")
- expression = strings.ReplaceAll(expression, " ::", "::")
- expression = strings.ReplaceAll(expression, ":: ", "::")
-
- // Handle parentheses around column names in function calls
- // Look for patterns like "function(columnname::type)" and convert to "function((columnname)::type)"
- // This is a simplified implementation for the specific case we're seeing
- if strings.Contains(expression, "lower(") && strings.Contains(expression, "::") {
- // Find the content inside lower()
- lowerIdx := strings.Index(expression, "lower(")
- if lowerIdx != -1 {
- start := lowerIdx + 6 // length of "lower("
- end := strings.LastIndex(expression, ")")
- if end > start {
- content := expression[start:end]
- // If content doesn't already have parentheses around the column name
- if strings.Contains(content, "::") && !strings.HasPrefix(content, "(") {
- // Split at :: to identify the column part
- parts := strings.SplitN(content, "::", 2)
- if len(parts) == 2 {
- columnPart := strings.TrimSpace(parts[0])
- typePart := strings.TrimSpace(parts[1])
- // Add parentheses around column name
- newContent := fmt.Sprintf("(%s)::%s", columnPart, typePart)
- expression = expression[:start] + newContent + expression[end:]
- }
- }
- }
- }
- }
-
- return expression
-}
-
-// normalizePostgreSQLCheckExpression normalizes check constraint expressions to match PostgreSQL system catalog format
-func (*metadataExtractor) normalizePostgreSQLCheckExpression(expression string) string {
- // Looking at the test output, we need to keep the sync format instead of normalizing to user-friendly format
- // Sync: (order_date >= (CURRENT_DATE - '1 year'::interval))
- // Parser should match the sync format, not try to normalize it
-
- // For now, return the expression as-is since the sync catalog uses the original PostgreSQL format
- // The differ should handle normalization between sync and parser formats
- return strings.TrimSpace(expression)
+ // Return the original text without any normalization
+ // This preserves the user's original input format
+ return ctx.GetParser().GetTokenStream().GetTextFromRuleContext(funcExpr)
}
// extractViewDependencies analyzes view definitions to extract dependencies using GetQuerySpan
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 f342a0495e..5d62647931 100644
--- a/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go
+++ b/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go
@@ -1109,13 +1109,11 @@ func compareIndexes(t *testing.T, tableName string, syncIndexes, parseIndexes []
// 10. IsConstraint - validate if index represents a constraint
require.Equal(t, syncIdx.IsConstraint, parseIdx.IsConstraint, "table %s, index %s: IsConstraint should match", tableName, name)
- // 11. Definition - validate full index definition for comprehensive verification
+ // 11. Definition - validate full index definition using AST-based semantic comparison
if syncIdx.Definition != "" || parseIdx.Definition != "" {
- // Normalize definitions for comparison since formatting may differ
- syncDef := strings.TrimSpace(strings.ToLower(syncIdx.Definition))
- parseDef := strings.TrimSpace(strings.ToLower(parseIdx.Definition))
- if syncDef != "" && parseDef != "" {
- require.Equal(t, syncDef, parseDef, "table %s, index %s: definition should match", tableName, name)
+ if syncIdx.Definition != "" && parseIdx.Definition != "" {
+ definitionsEqual := compareIndexDefinitionsSemanticaly(syncIdx.Definition, parseIdx.Definition)
+ require.True(t, definitionsEqual, "table %s, index %s: definition should match\nSync: %s\nParse: %s", tableName, name, syncIdx.Definition, parseIdx.Definition)
}
}
@@ -1772,3 +1770,198 @@ func validateRoutingRules(t *testing.T, metadata *storepb.DatabaseSchemaMetadata
t.Log("No rules in this test case - validation passed")
}
}
+
+// compareIndexDefinitionsSemanticaly compares two PostgreSQL index definitions using AST-based semantic comparison
+func compareIndexDefinitionsSemanticaly(def1, def2 string) bool {
+ if strings.TrimSpace(def1) == strings.TrimSpace(def2) {
+ return true
+ }
+
+ // Parse the index definitions to extract components
+ parts1 := parseIndexDefinition(def1)
+ parts2 := parseIndexDefinition(def2)
+
+ if parts1 == nil || parts2 == nil {
+ // Fallback to case-insensitive string comparison if parsing fails
+ return strings.EqualFold(strings.TrimSpace(def1), strings.TrimSpace(def2))
+ }
+
+ // Compare non-expression parts
+ if !strings.EqualFold(parts1.CreateClause, parts2.CreateClause) ||
+ !strings.EqualFold(parts1.IndexName, parts2.IndexName) ||
+ !strings.EqualFold(parts1.OnClause, parts2.OnClause) ||
+ !strings.EqualFold(parts1.UsingClause, parts2.UsingClause) {
+ return false
+ }
+
+ // Compare expressions using semantic comparison
+ comparer := ast.NewPostgreSQLExpressionComparer()
+ if parts1.ExpressionsClause != "" && parts2.ExpressionsClause != "" {
+ equal, err := comparer.CompareExpressions(parts1.ExpressionsClause, parts2.ExpressionsClause)
+ if err != nil {
+ // Fallback to string comparison if expression comparison fails
+ return strings.EqualFold(strings.TrimSpace(parts1.ExpressionsClause), strings.TrimSpace(parts2.ExpressionsClause))
+ }
+ if !equal {
+ return false
+ }
+ } else if parts1.ExpressionsClause != parts2.ExpressionsClause {
+ return false
+ }
+
+ // Compare WHERE clause using semantic comparison
+ if parts1.WhereClause != "" && parts2.WhereClause != "" {
+ equal, err := comparer.CompareExpressions(parts1.WhereClause, parts2.WhereClause)
+ if err != nil {
+ // Fallback to string comparison if expression comparison fails
+ return strings.EqualFold(strings.TrimSpace(parts1.WhereClause), strings.TrimSpace(parts2.WhereClause))
+ }
+ if !equal {
+ return false
+ }
+ } else if parts1.WhereClause != parts2.WhereClause {
+ return false
+ }
+
+ // Compare optional clauses
+ return strings.EqualFold(parts1.IncludeClause, parts2.IncludeClause) &&
+ strings.EqualFold(parts1.WithClause, parts2.WithClause)
+}
+
+// indexDefinitionParts represents the parsed components of an index definition
+type indexDefinitionParts struct {
+ CreateClause string // "CREATE [UNIQUE] INDEX"
+ IndexName string // index name
+ OnClause string // "ON table_name"
+ UsingClause string // "USING method"
+ ExpressionsClause string // column list or expressions inside parentheses
+ IncludeClause string // "INCLUDE (...)" clause
+ WhereClause string // WHERE condition (without WHERE keyword)
+ WithClause string // WITH (...) clause
+}
+
+// parseIndexDefinition parses a PostgreSQL index definition into its components
+func parseIndexDefinition(definition string) *indexDefinitionParts {
+ def := strings.TrimSpace(definition)
+ if def == "" {
+ return nil
+ }
+
+ // Remove trailing semicolon
+ def = strings.TrimSuffix(def, ";")
+
+ parts := &indexDefinitionParts{}
+
+ // Split by major keywords to identify parts
+ lowerDef := strings.ToLower(def)
+
+ // Find CREATE clause
+ createEnd := strings.Index(lowerDef, " on ")
+ if createEnd == -1 {
+ return nil
+ }
+
+ // Extract index name from CREATE clause
+ createPart := def[:createEnd]
+ parts.CreateClause = createPart
+
+ // Extract index name (last word before "on")
+ words := strings.Fields(createPart)
+ if len(words) > 0 {
+ parts.IndexName = words[len(words)-1]
+ }
+
+ remaining := def[createEnd:]
+ lowerRemaining := strings.ToLower(remaining)
+
+ // Find ON clause
+ usingPos := strings.Index(lowerRemaining, " using ")
+ if usingPos == -1 {
+ return nil
+ }
+ parts.OnClause = strings.TrimSpace(remaining[:usingPos])
+
+ remaining = remaining[usingPos:]
+
+ // Find USING clause
+ parenPos := strings.Index(remaining, "(")
+ if parenPos == -1 {
+ return nil
+ }
+ parts.UsingClause = strings.TrimSpace(remaining[:parenPos])
+
+ remaining = remaining[parenPos:]
+
+ // Extract expressions (content within first set of parentheses)
+ parenCount := 0
+ exprEnd := -1
+ for i, r := range remaining {
+ if r == '(' {
+ parenCount++
+ } else if r == ')' {
+ parenCount--
+ if parenCount == 0 {
+ exprEnd = i
+ break
+ }
+ }
+ }
+
+ if exprEnd == -1 {
+ return nil
+ }
+
+ // Extract content within parentheses (excluding the parentheses themselves)
+ parts.ExpressionsClause = strings.TrimSpace(remaining[1:exprEnd])
+
+ if len(remaining) > exprEnd+1 {
+ remaining = strings.TrimSpace(remaining[exprEnd+1:])
+ lowerRemaining = strings.ToLower(remaining)
+
+ // Look for optional clauses in order: INCLUDE, WHERE, WITH
+
+ // INCLUDE clause
+ if strings.HasPrefix(lowerRemaining, "include") {
+ includeEnd := strings.Index(remaining, ")")
+ if includeEnd != -1 {
+ parts.IncludeClause = strings.TrimSpace(remaining[:includeEnd+1])
+ if len(remaining) > includeEnd+1 {
+ remaining = strings.TrimSpace(remaining[includeEnd+1:])
+ lowerRemaining = strings.ToLower(remaining)
+ } else {
+ remaining = ""
+ lowerRemaining = ""
+ }
+ }
+ }
+
+ // WHERE clause
+ if strings.HasPrefix(lowerRemaining, "where ") {
+ whereStart := 6 // length of "where "
+ // Find the end of WHERE clause (could be end of string or start of WITH clause)
+ withPos := strings.Index(lowerRemaining, " with ")
+ var whereEnd int
+ if withPos != -1 {
+ whereEnd = withPos
+ } else {
+ whereEnd = len(remaining)
+ }
+ parts.WhereClause = strings.TrimSpace(remaining[whereStart:whereEnd])
+
+ if withPos != -1 {
+ remaining = strings.TrimSpace(remaining[withPos:])
+ lowerRemaining = strings.ToLower(remaining)
+ } else {
+ remaining = ""
+ lowerRemaining = ""
+ }
+ }
+
+ // WITH clause
+ if strings.HasPrefix(lowerRemaining, "with ") {
+ parts.WithClause = strings.TrimSpace(remaining)
+ }
+ }
+
+ return parts
+}