Cross-shard `SELECT DISTINCT` returns duplicate rows on MySQL when the column contains NULL
Bug Report
Which version of ShardingSphere did you use?
master @ 6f67b6b4579
Which project did you use? ShardingSphere-JDBC or ShardingSphere-Proxy?
Both. The problem is in result merging.
Expected behavior
SELECT DISTINCT user_id FROM t_order routed to two shards should return each value once: NULL, 10.
Actual behavior
It returns 10, NULL, 10, so 10 shows up twice.
Reason analyze (If you can)
For DISTINCT without GROUP BY / ORDER BY, OrderByContextEngine generates ORDER BY col ASC and passes getDefaultNullsOrderType() straight through. For MySQL that's LOW, which never gets resolved to FIRST/LAST: OrderByItemSegment#getNullsOrderType(DatabaseType) only resolves when the stored value is null. CompareUtils then treats anything other than FIRST as nulls-last.
So the stream merger's priority queue puts NULL last, while each MySQL shard returns NULL first for ASC. Equal values stop being adjacent and GroupByStreamMergedResult splits the group.
LOW/HIGH came in with #32813, which resolved it in ShardingProjectionsTokenGenerator but not here. Dialects defaulting to HIGH (PostgreSQL, Oracle, openGauss) aren't affected, because HIGH + ASC happens to mean nulls-last. MySQL, SQL Server, H2 and the other LOW dialects are affected.
Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc.
- MySQL,
t_ordersharded intot_order_0andt_order_1. t_order_0hasuser_idNULL and 10;t_order_1hasuser_id10.SELECT DISTINCT user_id FROM t_order;
Example codes for reproduce this issue (such as a github link).
Reproduced against ShardingDQLResultMerger with two query results [NULL, 10] and [10]: the merged output is [10, null, 10].
Source: apache/shardingsphere