kosiew opened a new issue, #27989:
URL: https://github.com/apache/datafusion/issues/27989

   ## Related PR
   #27333 
   
   ## Problem
   
   The SQL unparser loses the outer `LIMIT` when a logical plan has two
   literal `Limit` nodes stacked directly, without a projection, sort or
   aggregate between them. The generated SQL keeps only the inner limit and
   can return rows that the original plan discards.
   
   The public DataFrame API builds such plans without the optimizer
   (`DataFrame::limit` twice, then `into_unoptimized_plan`). Results below
   come from executing the plan and its `plan_to_sql` output in DataFusion,
   on `t = [1, 5, 11]` and on an empty table. The expected row count is 0 for
   every plan.
   
   | Plan | Generated SQL (default dialect) | Rows from `t` |
   | --- | --- | --- |
   | `scan(t).limit(1).limit(0)` | `SELECT * FROM t LIMIT 1` | 1 |
   | `scan(t).limit(1).limit(0).select([lit(7)])` | `SELECT 7 FROM (SELECT * 
FROM t LIMIT 1)` | 1 |
   | `scan(t).aggregate([], [count(lit(1))]).limit(1).limit(0)` | `SELECT 
count(1) FROM t LIMIT 1` | 1 (also 1 on the empty table) |
   | `scan(t).aggregate([], 
[count(lit(1))]).limit(1).limit(0).select([lit(7)])` | `SELECT 7 FROM (SELECT 
count(1) FROM t LIMIT 1)` | 1 (also 1 on the empty table) |
   
   (`.limit(n)` means `.limit(0, Some(n))`.)
   
   Offsets are affected too, because the two slots are overwritten
   independently. On `t` (empty-table results are correct here):
   
   | Plan | Generated SQL | Expected | Rows |
   | --- | --- | --- | --- |
   | `scan(t).limit(1, Some(2)).limit(0, Some(1))` | `SELECT * FROM t LIMIT 2 
OFFSET 1` | 1 | 2 |
   | `scan(t).limit(0, Some(2)).limit(1, Some(1))` | `SELECT * FROM t LIMIT 2 
OFFSET 1` | 1 | 2 |
   | `scan(t).limit(0, Some(1)).limit(2, None)` | `SELECT * FROM t LIMIT 1 
OFFSET 2` | 0 | 1 |
   
   In the last two plans the SQL mixes the outer limit's offset with the
   inner limit's fetch. PostgreSQL-dialect output has the same shape.
   
   The first three rows fail on `main`. The fourth fails after #27333, whose
   correct fix for a dropped global aggregate wraps the aggregate in a derived
   subquery. That subquery is now unparsed by the same `Limit` handler. Before
   #27333 the fourth plan rendered as `SELECT 7 FROM t LIMIT 0`, which was
   correct only because it also dropped the aggregate.
   
   Root cause: in `datafusion/sql/src/unparser/plan.rs`, the
   `LogicalPlan::Limit` arm of `select_to_sql_recursively` writes `fetch` and
   `skip` into the current `QueryBuilder` with `query.limit(..)` and
   `query.offset(..)`. It then recurses into its input. If that input is
   another `Limit`, the second write overwrites the first
   (`datafusion/sql/src/unparser/ast.rs`, the single `limit`/`offset` slots).
   The arm starts a derived query only when `select.already_projected()`,
   which is false between two adjacent limits.
   
   The projection path already merges adjacent literal limits with
   `combine_limit`, so `scan.aggregate(..).limit(1).limit(0).select([col])`
   is correct (`SELECT count(1) AS c FROM t LIMIT 0`). Plans whose root is a
   `Limit`, plans with column-free projections, and derived subqueries reach
   the bare handler instead.
   
   ## Why it matters
   
   The result is wrong with no error: the generated SQL is valid and runs in
   every dialect, but returns more rows than the plan. Federation and
   pushdown users run unparsed SQL against remote engines, so the error
   reaches their results. The optimizer's limit merging hides the bug for SQL
   input, but it does not protect callers that unparse unoptimized or
   hand-built plans.
   
   ## Invariant / desired behavior
   
   For any valid plan, the SQL produced by the unparser returns the same rows
   as the plan. A `Limit` (fetch and/or skip) must never overwrite a
   `LIMIT`/`OFFSET` already set in the query being built. Either merge the
   two with `combine_limit`, which applies only when both are literal, or put
   the inner limit in its own derived query.
   
   ## Proposed direction
   
   Fix this in the `LogicalPlan::Limit` arm rather than in each caller. When
   the current query already has a `LIMIT` or `OFFSET`, take the existing
   `derive_with_dialect_alias("derived_limit", ..)` branch, just as when the
   select is already projected.
   
   A local prototype confirmed this:
   
   ```rust
   // ast.rs, QueryBuilder (keep crate-private; QueryBuilder is reachable
   // through the public `unparser::ast` module)
   pub(super) fn has_limit_or_offset(&self) -> bool {
       self.limit.is_some() || self.offset.is_some()
   }
   
   // plan.rs, LogicalPlan::Limit arm
   if select.already_projected()
       || query.as_ref().is_some_and(|q| q.has_limit_or_offset())
   {
       return self.derive_with_dialect_alias("derived_limit", plan, relation, 
false, vec![]);
   }
   ```
   
   The prototype produced `SELECT * FROM (SELECT * FROM t LIMIT 1) LIMIT 0`
   and similar output for all four plans, with 0 rows on both inputs. It also
   fixed the three offset plans, for example
   `SELECT * FROM (SELECT * FROM t LIMIT 1) OFFSET 2`; PostgreSQL output adds
   `AS "derived_limit"`. With the helper as `pub(super)` it compiles. With
   it, the `datafusion-sql` `sql_integration` suite (614 tests), the unparser
   unit tests (44) and `core_integration sql::unparser` all passed.
   `cargo xtask ci step test unparser` was not run.
   
   Optional refinement: merge two adjacent literal limits with `combine_limit`
   to get one flat `LIMIT` instead of a nested query. Do this only if
   reviewers prefer that output. It adds a second code path, and correctness
   does not need it.
   
   ## Scope
   
   ### In
   
   - The `LogicalPlan::Limit` arm in `datafusion/sql/src/unparser/plan.rs`
     and a crate-private helper on `QueryBuilder`.
   - Regression tests for the four plan shapes above.
   
   ### Out
   
   - Changes to the projection path's Sort/Limit folding loop. It already
     handles its own shapes, and routing this fix through it would not cover
     bare `Limit` roots.
   - Interaction between `Sort` and `Limit` ordering (a separate invariant).
   - Optimizer changes. The bug concerns unoptimized plans, so running
     `PushDownLimit` first is not a fix.
   - New public API.
   
   ## Acceptance criteria
   
   - [ ] Each of the four plans above unparses to SQL that returns 0 rows in
         DataFusion on both a non-empty and an empty table.
   - [ ] `scan.limit(1).limit(0)` no longer renders as `... LIMIT 1` with
         the outer `LIMIT 0` lost; the generated SQL contains both limits or
         their exact combination.
   - [ ] Each of the three offset plans above returns the same rows as the
         plan (1, 1, 0 on `t`); the outer offset is never combined with the
         inner fetch in one `LIMIT ... OFFSET`.
   - [ ] Existing single-`Limit` output is unchanged (for example
         `SELECT ... LIMIT 1 OFFSET 1`, and the projection path's merged
         `LIMIT`), confirmed by unchanged snapshots in `plan_to_sql.rs`.
   - [ ] No new `pub` item. `QueryBuilder` helpers added for this fix are
         `pub(super)` or private.
   
   ## Tests / verification
   
   - Integration test in `datafusion/core/tests/sql/unparser.rs`: build each
     plan with the DataFrame API, execute both the plan and the generated
     SQL on 3-row and empty tables, and assert equal row counts. The same
     file already uses this pattern in
     `unparse_projection_without_columns_over_global_aggregate`.
   - Snapshot tests in `datafusion/sql/tests/cases/plan_to_sql.rs` for the
     default dialect and one dialect that requires derived-table aliases
     (PostgreSQL), which pins the `derived_limit` alias.
   - Run `cargo test -p datafusion-sql --test sql_integration`,
     `cargo test -p datafusion-sql --lib unparser`,
     `cargo test -p datafusion --test core_integration sql::unparser`, and
     `cargo xtask ci step test unparser`.
   
   
   


-- 
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]

Reply via email to