@@ -602,7 +602,7 @@ static PreAnalysisResult fieldNames(LogicalPlan parsed, Set<String> enrichPolicy
602602 var keepJoinRefsBuilder = AttributeSet .builder ();
603603 Set <String > wildcardJoinIndices = new java .util .HashSet <>();
604604
605- boolean [] canRemoveAliases = new boolean [] { true , true };
605+ boolean [] canRemoveAliases = new boolean [] { true };
606606
607607 parsed .forEachDown (p -> {// go over each plan top-down
608608 if (p instanceof RegexExtract re ) { // for Grok and Dissect
@@ -658,7 +658,7 @@ static PreAnalysisResult fieldNames(LogicalPlan parsed, Set<String> enrichPolicy
658658 //
659659 // and ips_policy enriches the results with the same name ip field),
660660 // these aliases should be kept in the list of fields.
661- if (canRemoveAliases [0 ] && couldOverrideAliases ( p )) {
661+ if (canRemoveAliases [0 ] && p . anyMatch ( EsqlSession :: couldOverrideAliases )) {
662662 canRemoveAliases [0 ] = false ;
663663 }
664664 if (canRemoveAliases [0 ]) {
@@ -667,22 +667,13 @@ static PreAnalysisResult fieldNames(LogicalPlan parsed, Set<String> enrichPolicy
667667 // remove the UnresolvedAttribute "x", since that is an Alias defined in "eval"
668668 AttributeSet planRefs = p .references ();
669669 Set <String > fieldNames = planRefs .names ();
670- canRemoveAliases [1 ] = true ;
671- // go down each plan and remove aliases until we meet a plan that can override aliases
672- p .forEachDown (c -> {
673- if (canRemoveAliases [1 ] && couldOverrideAliases (c )) {
674- canRemoveAliases [1 ] = false ;
675- }
676- if (canRemoveAliases [1 ]) {
677- c .forEachExpression (Alias .class , alias -> {
678- // do not remove the UnresolvedAttribute that has the same name as its alias, ie "rename id AS id"
679- // or the UnresolvedAttributes that are used in Functions that have aliases "STATS id = MAX(id)"
680- if (fieldNames .contains (alias .name ())) {
681- return ;
682- }
683- referencesBuilder .removeIf (attr -> matchByName (attr , alias .name (), shadowingRefsBuilder .contains (attr )));
684- });
670+ p .forEachExpressionDown (Alias .class , alias -> {
671+ // do not remove the UnresolvedAttribute that has the same name as its alias, ie "rename id AS id"
672+ // or the UnresolvedAttributes that are used in Functions that have aliases "STATS id = MAX(id)"
673+ if (fieldNames .contains (alias .name ())) {
674+ return ;
685675 }
676+ referencesBuilder .removeIf (attr -> matchByName (attr , alias .name (), shadowingRefsBuilder .contains (attr )));
686677 });
687678 }
688679 });
@@ -733,7 +724,8 @@ private static boolean couldOverrideAliases(LogicalPlan p) {
733724 || p instanceof Project
734725 || p instanceof RegexExtract
735726 || p instanceof Rename
736- || p instanceof TopN ) == false ;
727+ || p instanceof TopN
728+ || p instanceof UnresolvedRelation ) == false ;
737729 }
738730
739731 private static boolean matchByName (Attribute attr , String other , boolean skipIfPattern ) {
0 commit comments