Skip to content

Commit 2fa9df9

Browse files
committed
fix: allow sort on aggregate aliases in groupBy queries
Sort column validation now accepts aggregate output names (e.g., "avg_amt") and group-by columns, not just source schema columns. Fixes groupBy + sort + limit pattern like .groupBy("customer_id").aggregate("avg", "amount", "avg_amt").sort("avg_amt", "desc").
1 parent 07f3e84 commit 2fa9df9

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/local-executor.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,11 @@ export class LocalExecutor implements QueryExecutor {
441441
}
442442
}
443443
if (query.sortColumn && !columnNames.has(query.sortColumn)) {
444-
throw new QueryModeError("COLUMN_NOT_FOUND", `Sort column "${query.sortColumn}" not found in ${query.table}. Available: ${[...columnNames].join(", ")}`);
444+
const aggAliases = new Set((query.aggregates ?? []).map(a => a.alias ?? `${a.fn}_${a.column}`));
445+
const groupCols = new Set(query.groupBy ?? []);
446+
if (!aggAliases.has(query.sortColumn) && !groupCols.has(query.sortColumn)) {
447+
throw new QueryModeError("COLUMN_NOT_FOUND", `Sort column "${query.sortColumn}" not found in ${query.table}. Available: ${[...columnNames].join(", ")}`);
448+
}
445449
}
446450

447451
// Step 2: Determine columns to fetch (projection + filter + sort columns)
@@ -667,7 +671,12 @@ export class LocalExecutor implements QueryExecutor {
667671
}
668672
}
669673
if (query.sortColumn && !schemaColumnNames.has(query.sortColumn)) {
670-
throw new QueryModeError("COLUMN_NOT_FOUND", `Sort column "${query.sortColumn}" not found in ${query.table}. Available: ${[...schemaColumnNames].join(", ")}`);
674+
// Allow sorting by aggregate output aliases (e.g., "avg_amount", "sum_revenue")
675+
const aggAliases = new Set((query.aggregates ?? []).map(a => a.alias ?? `${a.fn}_${a.column}`));
676+
const groupCols = new Set(query.groupBy ?? []);
677+
if (!aggAliases.has(query.sortColumn) && !groupCols.has(query.sortColumn)) {
678+
throw new QueryModeError("COLUMN_NOT_FOUND", `Sort column "${query.sortColumn}" not found in ${query.table}. Available: ${[...schemaColumnNames].join(", ")}`);
679+
}
671680
}
672681

673682
// Execute query across all fragments

0 commit comments

Comments
 (0)