davidlghellin opened a new pull request, #19736:
URL: https://github.com/apache/datafusion/pull/19736

   ## Which issue does this PR close?
   
   - Closes https://github.com/apache/datafusion/issues/19735.
   
   ## Rationale for this change
   
   The `SingleDistinctToGroupBy` optimizer rewrites aggregate functions with 
`DISTINCT` into a `GROUP BY` operation for better performance. However, during 
this rewrite, it was discarding important aggregate function parameters: 
`null_treatment`, `filter`, and `order_by`.
   
   This caused queries like `ARRAY_AGG(DISTINCT x IGNORE NULLS)` to include 
NULL values in the result because the `IGNORE NULLS` clause (stored as 
null_treatment) was being lost during optimization.
   
   ## What changes are included in this PR?
   
   Preserve aggregate parameters in optimizer: Modified 
`SingleDistinctToGroupBy` to extract and preserve `null_treatment`, `filter`, 
and `order_by` from the original aggregate function when creating the rewritten 
version.
   
   Add regression test: Added SQL logic test to verify that `ARRAY_AGG(DISTINCT 
x IGNORE NULLS)` correctly filters out NULL values.
   
   Files changed:
   
   **datafusion/optimizer/src/single_distinct_to_groupby.rs**: Extract and pass 
through filter, order_by, and null_treatment parameters
   **datafusion/sqllogictest/test_files/aggregate.slt**: Add test case for 
ARRAY_AGG(DISTINCT ... IGNORE NULLS)
   
   ## Are these changes tested?
   
   Yes:
   New SQL logic test in aggregate.slt verifies the fix works end-to-end
   Existing optimizer tests continue to pass (19 tests in 
`single_distinct_to_groupby`)
   Existing aggregate tests continue to pass (20 tests in `array_agg`)
   
   ## Are there any user-facing changes?
   
   Bug fix - Users can now correctly use `IGNORE NULLS` (and `FILTER` / `ORDER 
BY`) with `DISTINCT` aggregates:
   
   Before (broken):
   
   ```sql
   SELECT ARRAY_AGG(DISTINCT x IGNORE NULLS) 
   FROM (VALUES (1), (2), (NULL), (2), (1)) AS t(x);
   -- Result: [2, NULL, 1]  ❌ NULL incorrectly included
   ```
   
   After (fixed):
   ```sql
   SELECT ARRAY_AGG(DISTINCT x IGNORE NULLS) 
   FROM (VALUES (1), (2), (NULL), (2), (1)) AS t(x);
   -- Result: [1, 2]  ✅ NULLs correctly filtered
   ```


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