Browse Source

SQL: Fix bug in resolving aliases against filters (#58399)

When doing aliasing with the same name over non existing fields, the analyzer gets stuck in a loop trying to resolve the alias over and over leading to SO. This PR breaks the cycle by checking the relationship between the alias and the child it tries to replace as an alias should never replace its child.

Fix #57270
Close #57417
Co-authored-by: Hailei <zhh5919@163.com>
Costin Leau 5 years ago
parent
commit
46786ff2e1

+ 6 - 2
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java

@@ -852,7 +852,11 @@ public class Analyzer extends RuleExecutor<LogicalPlan> {
             return condition.transformDown(u -> {
                 boolean qualified = u.qualifier() != null;
                 for (Alias alias : aliases) {
-                    if (qualified ? Objects.equals(alias.qualifiedName(), u.qualifiedName()) : Objects.equals(alias.name(), u.name())) {
+                    // don't replace field with their own aliases (it creates infinite cycles)
+                    if (u != alias.child() &&
+                           (qualified ?
+                               Objects.equals(alias.qualifiedName(), u.qualifiedName()) :
+                               Objects.equals(alias.name(), u.name()))) {
                         return alias;
                     }
                 }
@@ -1299,7 +1303,7 @@ public class Analyzer extends RuleExecutor<LogicalPlan> {
             return true;
         }
     }
-    
+
     abstract static class BaseAnalyzeRule extends AnalyzeRule<LogicalPlan> {
 
         @Override

+ 8 - 0
x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerifierErrorMessagesTests.java

@@ -1022,6 +1022,14 @@ public class VerifierErrorMessagesTests extends ESTestCase {
         assertEquals("1:8: Unknown column [tni]", error("SELECT tni AS i FROM test WHERE i > 10 GROUP BY i"));
     }
 
+    public void testProjectUnresolvedAliasWithSameNameInFilter() {
+        assertEquals("1:8: Unknown column [i]", error("SELECT i AS i FROM test WHERE i > 10 GROUP BY i"));
+    }
+
+    public void testProjectUnresolvedAliasWithSameNameInOrderBy() {
+        assertEquals("1:8: Unknown column [i]", error("SELECT i AS i FROM test ORDER BY i"));
+    }
+
     public void testGeoShapeInWhereClause() {
         assertEquals("1:49: geo shapes cannot be used for filtering",
             error("SELECT ST_AsWKT(shape) FROM test WHERE ST_AsWKT(shape) = 'point (10 20)'"));