Skip to content

Apache DataFusion SQL Query Engine

fix union view (#15300)

Jay Zhan6c5c5c15e455
diff --git a/datafusion/sqllogictest/test_files/union.slt b/datafusion/sqllogictest/test_files/union.slt
index 654bccfab5..1cf648510b 100644
--- a/datafusion/sqllogictest/test_files/union.slt
+++ b/datafusion/sqllogictest/test_files/union.slt
@@ -896,7 +896,7 @@ INSERT INTO u2 VALUES (20, 20), (40, 40);
statement ok
CREATE VIEW v1 AS
-SELECT y FROM u1 UNION ALL SELECT y FROM u2 ORDER BY y;
+SELECT y FROM u1 UNION ALL SELECT y FROM u2 ORDER BY y;
query I
SELECT * FROM (SELECT y FROM u1 UNION ALL SELECT y FROM u2) ORDER BY y;
@@ -907,11 +907,56 @@ SELECT * FROM (SELECT y FROM u1 UNION ALL SELECT y FROM u2) ORDER BY y;
20
40
+query TT
+explain SELECT * FROM (SELECT y FROM u1 UNION ALL SELECT y FROM u2) ORDER BY y;
+----
+logical_plan
+01)Sort: y ASC NULLS LAST
+02)--Union
+03)----Projection: CAST(u1.y AS Int64) AS y
+04)------TableScan: u1 projection=[y]
+05)----TableScan: u2 projection=[y]
+physical_plan
+01)SortPreservingMergeExec: [y@0 ASC NULLS LAST]
+02)--UnionExec
+03)----SortExec: expr=[y@0 ASC NULLS LAST], preserve_partitioning=[true]
+04)------ProjectionExec: expr=[CAST(y@0 AS Int64) as y]
+05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
+06)----------DataSourceExec: partitions=1, partition_sizes=[1]
+07)----SortExec: expr=[y@0 ASC NULLS LAST], preserve_partitioning=[false]
+08)------DataSourceExec: partitions=1, partition_sizes=[1]
+
+# optimize_subquery_sort in create_relation removes Sort so the result is not sorted.
query I
SELECT * FROM v1;
----
-1
-3
-3
20
40
+3
+3
+1
+
+query TT
+explain SELECT * FROM v1;
+----
+logical_plan
+01)SubqueryAlias: v1
+02)--Union
+03)----Projection: CAST(u1.y AS Int64) AS y
+04)------TableScan: u1 projection=[y]
+05)----TableScan: u2 projection=[y]
+physical_plan
+01)UnionExec
+02)--ProjectionExec: expr=[CAST(y@0 AS Int64) as y]
+03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
+04)------DataSourceExec: partitions=1, partition_sizes=[1]
+05)--DataSourceExec: partitions=1, partition_sizes=[1]
+
+statement count 0
+drop view v1;
+
+statement count 0
+drop table u1;
+
+statement count 0
+drop table u2;