Skip to content

Commit

Permalink
[CALCITE-5768] JDBC adapter should insert a subquery for a query with…
Browse files Browse the repository at this point in the history
… ORDER BY ordinal

The incorrect query has an ordinal that is not the first item
of the ORDER BY clause:

  SELECT "JOB"
  FROM "scott"."EMP"
  GROUP BY "JOB"
  ORDER BY "JOB", 2

The correct query should have a subquery:

  SELECT "JOB"
  FROM (SELECT "JOB", COUNT("ENAME") AS "$f1"
    FROM "scott"."EMP"
    GROUP BY "JOB"
    ORDER BY "JOB", 2) AS "t0"
  • Loading branch information
wnob authored and julianhyde committed Jun 8, 2023
1 parent 821f03b commit cf7f71b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1898,12 +1898,14 @@ private boolean hasSortByOrdinal(@UnknownInitialization Result this) {
return false;
}
for (SqlNode sqlNode : orderList) {
if (!(sqlNode instanceof SqlBasicCall)) {
return sqlNode instanceof SqlNumericLiteral;
if (sqlNode instanceof SqlNumericLiteral) {
return true;
}
for (SqlNode operand : ((SqlBasicCall) sqlNode).getOperandList()) {
if (operand instanceof SqlNumericLiteral) {
return true;
if (sqlNode instanceof SqlBasicCall) {
for (SqlNode operand : ((SqlBasicCall) sqlNode).getOperandList()) {
if (operand instanceof SqlNumericLiteral) {
return true;
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,24 @@ private static String toSql(RelNode root, SqlDialect dialect,
relFn(relFn).ok(expected);
}

@Test void testUsesSubqueryWhenSortingByIdThenOrdinal() {
final Function<RelBuilder, RelNode> relFn = b -> b
.scan("EMP")
.aggregate(
b.groupKey("JOB"),
b.aggregateCall(SqlStdOperatorTable.COUNT, b.field("ENAME")))
.sort(b.field(0), b.field(1))
.project(b.field(0))
.build();
final String expected = "SELECT \"JOB\"\n"
+ "FROM (SELECT \"JOB\", COUNT(\"ENAME\") AS \"$f1\"\n"
+ "FROM \"scott\".\"EMP\"\n"
+ "GROUP BY \"JOB\"\n"
+ "ORDER BY \"JOB\", 2) AS \"t0\"";

relFn(relFn).ok(expected);
}

@Test void testSelectQueryWithWhereClauseOfBasicOperators() {
String query = "select * from \"product\" "
+ "where (\"product_id\" = 10 OR \"product_id\" <= 5) "
Expand Down

0 comments on commit cf7f71b

Please sign in to comment.