Skip to content

Commit c4766ed

Browse files
ES|QL: fix validation of SORT by aggregate functions (elastic#117316) (elastic#117328)
1 parent a3f995b commit c4766ed

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

docs/changelog/117316.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
pr: 117316
2+
summary: Fix validation of SORT by aggregate functions
3+
area: ES|QL
4+
type: bug
5+
issues: []

x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/analysis/Verifier.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ else if (p instanceof Lookup lookup) {
193193
checkOperationsOnUnsignedLong(p, failures);
194194
checkBinaryComparison(p, failures);
195195
checkForSortableDataTypes(p, failures);
196+
checkSort(p, failures);
196197

197198
checkFilterMatchConditions(p, failures);
198199
checkFullTextQueryFunctions(p, failures);
@@ -207,6 +208,18 @@ else if (p instanceof Lookup lookup) {
207208
return failures;
208209
}
209210

211+
private void checkSort(LogicalPlan p, Set<Failure> failures) {
212+
if (p instanceof OrderBy ob) {
213+
ob.order().forEach(o -> {
214+
o.forEachDown(Function.class, f -> {
215+
if (f instanceof AggregateFunction) {
216+
failures.add(fail(f, "Aggregate functions are not allowed in SORT [{}]", f.functionName()));
217+
}
218+
});
219+
});
220+
}
221+
}
222+
210223
private static void checkFilterConditionType(LogicalPlan p, Set<Failure> localFailures) {
211224
if (p instanceof Filter f) {
212225
Expression condition = f.condition();

x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/analysis/VerifierTests.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1580,6 +1580,13 @@ public void testToDatePeriodToTimeDurationWithInvalidType() {
15801580
);
15811581
}
15821582

1583+
public void testSortByAggregate() {
1584+
assertEquals("1:18: Aggregate functions are not allowed in SORT [COUNT]", error("ROW a = 1 | SORT count(*)"));
1585+
assertEquals("1:28: Aggregate functions are not allowed in SORT [COUNT]", error("ROW a = 1 | SORT to_string(count(*))"));
1586+
assertEquals("1:22: Aggregate functions are not allowed in SORT [MAX]", error("ROW a = 1 | SORT 1 + max(a)"));
1587+
assertEquals("1:18: Aggregate functions are not allowed in SORT [COUNT]", error("FROM test | SORT count(*)"));
1588+
}
1589+
15831590
private void query(String query) {
15841591
defaultAnalyzer.analyze(parser.createStatement(query));
15851592
}

0 commit comments

Comments
 (0)