Skip to content

Commit

Permalink
[CALCITE-1610] RelBuilder sort-combining optimization treats aliases …
Browse files Browse the repository at this point in the history
…incorrectly (Jess Balint)

Close apache#367
  • Loading branch information
jbalint authored and julianhyde committed Jan 28, 2017
1 parent 3f955ee commit beb4653
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
9 changes: 5 additions & 4 deletions core/src/main/java/org/apache/calcite/tools/RelBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -1541,12 +1541,13 @@ public RelBuilder sortLimit(int offset, int fetch,
if (project.getInput() instanceof Sort) {
final Sort sort2 = (Sort) project.getInput();
if (sort2.offset == null && sort2.fetch == null) {
replaceTop(sort2.getInput());
final RelNode sort =
sortFactory.createSort(peek(), sort2.collation,
sortFactory.createSort(sort2.getInput(), sort2.collation,
offsetNode, fetchNode);
replaceTop(sort);
project(project.getProjects());
replaceTop(
projectFactory.createProject(sort,
project.getProjects(),
Pair.right(project.getNamedProjects())));
return this;
}
}
Expand Down
26 changes: 26 additions & 0 deletions core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1518,6 +1518,32 @@ private String str(RelNode r) {
assertThat(str(root), is(expected));
}

/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1610">[CALCITE-1610]
* RelBuilder sort-combining optimization treats aliases incorrectly</a>. */
@Test public void testSortOverProjectSort() {
final RelBuilder builder = RelBuilder.create(config().build());
builder.scan("EMP")
.sort(0)
.project(builder.field(1))
// was throwing exception here when attempting to apply to
// inner sort node
.limit(0, 1)
.build();
RelNode r = builder.scan("EMP")
.sort(0)
.project(Lists.newArrayList(builder.field(1)),
Lists.newArrayList("F1"))
.limit(0, 1)
// make sure we can still access the field by alias
.project(builder.field("F1"))
.build();
String expected = "LogicalProject(F1=[$1])\n"
+ " LogicalSort(sort0=[$0], dir0=[ASC], fetch=[1])\n"
+ " LogicalTableScan(table=[[scott, EMP]])\n";
assertThat(str(r), is(expected));
}

/** Tests that a sort on a field followed by a limit gives the same
* effect as calling sortLimit.
*
Expand Down

0 comments on commit beb4653

Please sign in to comment.