Skip to content

Commit 12cb5a4

Browse files
simonvandelalamb
authored andcommitted
fix: do not remove DISTINCT when a unique key was downgraded by a join (apache#23548)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes apache#123` indicates that this PR will close issue apache#123. --> - Closes apache#23626. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> The `ReplaceDistinctWithAggregate` optimization pass was incorrectly removing deduplication. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> First commit reproduces the bug in an SLT. I opted for SLT instead of a test inside `datafusion/optimizer/src/replace_distinct_aggregate.rs` since SLT seems easier to maintain. But let me know if you prefer the test elsewhere. Second commit fixes the bug. Also includes a drive-by documentation change for `Dependency` to surface the field docs. ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Yes ## Are there any user-facing changes? Yes, query now deduplicates correctly <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. --> --------- Co-authored-by: Andrew Lamb <[email protected]>
1 parent c8004a7 commit 12cb5a4

3 files changed

Lines changed: 66 additions & 6 deletions

File tree

‎datafusion/common/src/functional_dependencies.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,10 @@ pub struct FunctionalDependence {
151151
/// Describes functional dependency mode.
152152
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153153
pub enum Dependency {
154-
Single, // A determinant key may occur only once.
155-
Multi, // A determinant key may occur multiple times (in multiple rows).
154+
/// A determinant key may occur only once.
155+
Single,
156+
/// A determinant key may occur multiple times (in multiple rows).
157+
Multi,
156158
}
157159

158160
impl FunctionalDependence {

‎datafusion/optimizer/src/replace_distinct_aggregate.rs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use crate::{OptimizerConfig, OptimizerRule};
2222
use std::sync::Arc;
2323

2424
use datafusion_common::tree_node::Transformed;
25-
use datafusion_common::{Column, Result};
25+
use datafusion_common::{Column, Dependency, Result};
2626
use datafusion_expr::expr_rewriter::normalize_cols;
2727
use datafusion_expr::utils::expand_wildcard;
2828
use datafusion_expr::{Aggregate, Distinct, DistinctOn, Expr, LogicalPlan};
@@ -101,9 +101,14 @@ impl OptimizerRule for ReplaceDistinctWithAggregate {
101101

102102
let field_count = input.schema().fields().len();
103103
for dep in input.schema().functional_dependencies().iter() {
104-
// If distinct is exactly the same with a previous GROUP BY, we can
105-
// simply remove it:
106-
if dep.source_indices.len() >= field_count
104+
// If the input is already unique on all of its columns (e.g.
105+
// it is a GROUP BY over exactly these columns), the DISTINCT
106+
// is a no-op and we can simply remove it. The dependency mode
107+
// must be `Single`: a `Multi` dependence (e.g. a former key
108+
// downgraded by a join) means equal rows may occur multiple
109+
// times, so the DISTINCT still has work to do.
110+
if dep.mode == Dependency::Single
111+
&& dep.source_indices.len() >= field_count
107112
&& dep.source_indices[..field_count]
108113
.iter()
109114
.enumerate()

‎datafusion/sqllogictest/test_files/group_by.slt‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5641,3 +5641,56 @@ set datafusion.execution.target_partitions = 4;
56415641

56425642
statement count 0
56435643
drop table t;
5644+
5645+
# DISTINCT must not be removed when a unique key is downgraded to a
5646+
# non-unique functional dependency by a join: `u.id` is a primary key, but
5647+
# after the LEFT JOIN each `u` row can occur once per matching order.
5648+
statement ok
5649+
CREATE TABLE users_with_pk (id INT, name VARCHAR, primary key(id)) AS VALUES
5650+
(1, 'alice'),
5651+
(2, 'bob');
5652+
5653+
statement ok
5654+
CREATE TABLE user_orders (user_id INT, amount INT) AS VALUES
5655+
(1, 10),
5656+
(1, 20),
5657+
(2, 30);
5658+
5659+
query I
5660+
SELECT DISTINCT u.id
5661+
FROM users_with_pk u
5662+
LEFT JOIN user_orders o ON u.id = o.user_id
5663+
ORDER BY u.id;
5664+
----
5665+
1
5666+
2
5667+
5668+
# The DISTINCT must be planned as an Aggregate; it cannot be removed based
5669+
# on the (join-downgraded) primary key of `users_with_pk`.
5670+
query TT
5671+
EXPLAIN SELECT DISTINCT u.id
5672+
FROM users_with_pk u
5673+
LEFT JOIN user_orders o ON u.id = o.user_id;
5674+
----
5675+
logical_plan
5676+
01)Aggregate: groupBy=[[u.id]], aggr=[[]]
5677+
02)--Projection: u.id
5678+
03)----Left Join: u.id = o.user_id
5679+
04)------SubqueryAlias: u
5680+
05)--------TableScan: users_with_pk projection=[id]
5681+
06)------SubqueryAlias: o
5682+
07)--------TableScan: user_orders projection=[user_id]
5683+
physical_plan
5684+
01)AggregateExec: mode=FinalPartitioned, gby=[id@0 as id], aggr=[]
5685+
02)--RepartitionExec: partitioning=Hash([id@0], 4), input_partitions=4
5686+
03)----AggregateExec: mode=Partial, gby=[id@0 as id], aggr=[]
5687+
04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
5688+
05)--------HashJoinExec: mode=CollectLeft, join_type=Left, on=[(id@0, user_id@0)], projection=[id@0]
5689+
06)----------DataSourceExec: partitions=1, partition_sizes=[1]
5690+
07)----------DataSourceExec: partitions=1, partition_sizes=[1]
5691+
5692+
statement ok
5693+
drop table users_with_pk;
5694+
5695+
statement ok
5696+
drop table user_orders;

0 commit comments

Comments
 (0)