jayzhan211 opened a new pull request, #24958:
URL: https://github.com/apache/datafusion/pull/24958
## Which issue does this PR close?
- Closes #.
## Rationale for this change
`ORDER BY` applied on top of a `LIMIT ... OFFSET` subquery returns too few
rows.
```sql
SELECT * FROM (SELECT a FROM t1 LIMIT 4 OFFSET 3) ORDER BY a;
```
`EnforceSorting` pushes the sort below the `GlobalLimitExec` and converts it
into a
TopK. The TopK's fetch was seeded from `GlobalLimitExec::fetch()`, which is
the
limit's *output* row count and ignores `skip`. So the TopK kept only 4 rows,
the
limit then skipped 3 of them, and the query returned a single row instead of
4.
The same seeding happens in two places in `sort_pushdown.rs`: when a root's
direct
child is a `GlobalLimitExec` (`assign_initial_requirements`) and when the
pushdown
descends through one (`pushdown_sorts_helper`). Both had the bug.
## What changes are included in this PR?
- Add an `input_fetch` helper in `sort_pushdown.rs` that returns `skip +
fetch` for
`GlobalLimitExec` and plain `fetch()` for every other operator.
- Use it at both sites where the pushed-down fetch is derived from the plan
node, so
the TopK below a `GlobalLimitExec` retains enough rows for the limit to
skip and
still return `fetch` rows.
## What is the testing strategy for this PR?
- `limit.slt`: new `EXPLAIN` + result test for `LIMIT 4 OFFSET 3` under
`ORDER BY`,
showing `TopK(fetch=7)` below `GlobalLimitExec: skip=3, fetch=4` and the
correct
4 rows.
- `ensure_requirements.rs`: two unit tests, one per code path
(`test_sort_pushed_below_limit_with_skip_keeps_skip_rows` and
`test_parent_ordering_over_limit_with_skip_keeps_skip_rows`), asserting the
pushed sort has `fetch=15` for `skip=5, fetch=10`.
## Are there any user-facing changes?
Queries with a sort above `LIMIT ... OFFSET` now return the correct number
of rows.
No API changes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]