Context newContext = new Context(context);
final int sortKeyNum = node.getSortKeys().length;
String [] keyNames = new String[sortKeyNum];
for (int i = 0; i < sortKeyNum; i++) {
SortSpec sortSpec = node.getSortKeys()[i];
keyNames[i] = newContext.addExpr(new FieldEval(sortSpec.getSortKey()));
}
LogicalNode child = super.visitSort(newContext, plan, block, node, stack);
// it rewrite sortkeys. This rewrite sets right column names and eliminates duplicated sort keys.
List<SortSpec> sortSpecs = new ArrayList<SortSpec>();
for (int i = 0; i < keyNames.length; i++) {
String sortKey = keyNames[i];
Target target = context.targetListMgr.getTarget(sortKey);
if (context.targetListMgr.isEvaluated(sortKey)) {
Column c = target.getNamedColumn();
SortSpec sortSpec = new SortSpec(c, node.getSortKeys()[i].isAscending(), node.getSortKeys()[i].isNullFirst());
if (!sortSpecs.contains(sortSpec)) {
sortSpecs.add(sortSpec);
}
} else {
if (target.getEvalTree().getType() == EvalType.FIELD) {
Column c = ((FieldEval)target.getEvalTree()).getColumnRef();
SortSpec sortSpec = new SortSpec(c, node.getSortKeys()[i].isAscending(), node.getSortKeys()[i].isNullFirst());
if (!sortSpecs.contains(sortSpec)) {
sortSpecs.add(sortSpec);
}
}
}