@@ -842,9 +842,10 @@ public RelNode visitExpand(Expand expand, CalcitePlanContext context) {
842842
843843 RelBuilder relBuilder = context .relBuilder ;
844844
845- // 2. Get the field to expand
845+ // 2. Get the field to expand and an optional alias.
846846 Field arrayField = expand .getField ();
847847 RexInputRef arrayFieldRex = (RexInputRef ) rexVisitor .analyze (arrayField , context );
848+ String alias = expand .getAlias ();
848849
849850 // 3. Capture the outer row in a CorrelationId
850851 Holder <RexCorrelVariable > correlVariable = Holder .empty ();
@@ -860,7 +861,7 @@ public RelNode visitExpand(Expand expand, CalcitePlanContext context) {
860861
861862 // 5. Filter rows where the array field is the same as the left side
862863 // TODO: This is not a standard way to use correlate and uncollect together.
863- // A filter should not be necessary. Correct it in the future.
864+ // A filter should not be necessary. Correct it in the future.
864865 RexNode filterCondition = relBuilder .equals (correlArrayField , arrayFieldRex );
865866 relBuilder .filter (filterCondition );
866867
@@ -876,9 +877,17 @@ public RelNode visitExpand(Expand expand, CalcitePlanContext context) {
876877 // be used by the right side to correlate with the left side.
877878 relBuilder .correlate (JoinRelType .INNER , correlVariable .get ().id , List .of (arrayFieldRex ));
878879
879- // 8. Remove the original array field from the output. No alias is currently supported in the
880- // expand command, so it can be safely deleted. Its name is re-used for the expanded element.
880+ // 8. Remove the original array field from the output.
881+ // TODO: RFC: should we keep the original array field when alias is present?
881882 relBuilder .projectExcept (arrayFieldRex );
883+ if (alias != null ) {
884+ // Sub-nested fields cannot be removed after renaming the nested field.
885+ tryToRemoveNestedFields (context );
886+ RexInputRef expandedField = relBuilder .field (arrayField .getField ().toString ());
887+ List <String > names = new ArrayList <>(relBuilder .peek ().getRowType ().getFieldNames ());
888+ names .set (expandedField .getIndex (), alias );
889+ relBuilder .rename (names );
890+ }
882891 return relBuilder .peek ();
883892 }
884893}
0 commit comments