Apache DataFusion SQL Query Engine
Support Full Join (#291)
Daniël Heres03de07efc812
diff --git a/README.md b/README.mdindex 2f6640f28f..bc153368e1 100644--- a/README.md+++ b/README.md@@ -215,8 +215,8 @@ DataFusion also includes a simple command-line interactive SQL utility. See the- [x] INNER JOIN- [x] LEFT JOIN- [x] RIGHT JOIN+ - [x] FULL JOIN- [x] CROSS JOIN- - [ ] OUTER JOIN- [ ] Window## Data Sourcesdiff --git a/ballista/rust/core/proto/ballista.proto b/ballista/rust/core/proto/ballista.protoindex 381221f38d..07419d09b7 100644--- a/ballista/rust/core/proto/ballista.proto+++ b/ballista/rust/core/proto/ballista.proto@@ -292,6 +292,7 @@ enum JoinType {INNER = 0;LEFT = 1;RIGHT = 2;+ FULL = 3;}message JoinNode {diff --git a/ballista/rust/core/src/serde/logical_plan/from_proto.rs b/ballista/rust/core/src/serde/logical_plan/from_proto.rsindex ab7c55f450..6987035394 100644--- a/ballista/rust/core/src/serde/logical_plan/from_proto.rs+++ b/ballista/rust/core/src/serde/logical_plan/from_proto.rs@@ -235,6 +235,7 @@ impl TryInto<LogicalPlan> for &protobuf::LogicalPlanNode {protobuf::JoinType::Inner => JoinType::Inner,protobuf::JoinType::Left => JoinType::Left,protobuf::JoinType::Right => JoinType::Right,+ protobuf::JoinType::Full => JoinType::Full,};LogicalPlanBuilder::from(&convert_box_required!(join.left)?).join(diff --git a/ballista/rust/core/src/serde/logical_plan/to_proto.rs b/ballista/rust/core/src/serde/logical_plan/to_proto.rsindex de4b86e384..01b669d264 100644--- a/ballista/rust/core/src/serde/logical_plan/to_proto.rs+++ b/ballista/rust/core/src/serde/logical_plan/to_proto.rs@@ -808,6 +808,7 @@ impl TryInto<protobuf::LogicalPlanNode> for &LogicalPlan {JoinType::Inner => protobuf::JoinType::Inner,JoinType::Left => protobuf::JoinType::Left,JoinType::Right => protobuf::JoinType::Right,+ JoinType::Full => protobuf::JoinType::Full,};let left_join_column = on.iter().map(|on| on.0.to_owned()).collect();let right_join_column = on.iter().map(|on| on.1.to_owned()).collect();diff --git a/ballista/rust/core/src/serde/physical_plan/from_proto.rs b/ballista/rust/core/src/serde/physical_plan/from_proto.rsindex be0777dbb9..6a33c6a43f 100644--- a/ballista/rust/core/src/serde/physical_plan/from_proto.rs+++ b/ballista/rust/core/src/serde/physical_plan/from_proto.rs@@ -297,6 +297,7 @@ impl TryInto<Arc<dyn ExecutionPlan>> for &protobuf::PhysicalPlanNode {protobuf::JoinType::Inner => JoinType::Inner,protobuf::JoinType::Left => JoinType::Left,protobuf::JoinType::Right => JoinType::Right,+ protobuf::JoinType::Full => JoinType::Full,};Ok(Arc::new(HashJoinExec::try_new(left,diff --git a/ballista/rust/core/src/serde/physical_plan/to_proto.rs b/ballista/rust/core/src/serde/physical_plan/to_proto.rsindex 5352c1f777..8a5fd71083 100644--- a/ballista/rust/core/src/serde/physical_plan/to_proto.rs+++ b/ballista/rust/core/src/serde/physical_plan/to_proto.rs@@ -132,6 +132,7 @@ impl TryInto<protobuf::PhysicalPlanNode> for Arc<dyn ExecutionPlan> {JoinType::Inner => protobuf::JoinType::Inner,JoinType::Left => protobuf::JoinType::Left,JoinType::Right => protobuf::JoinType::Right,+ JoinType::Full => protobuf::JoinType::Full,};Ok(protobuf::PhysicalPlanNode {physical_plan_type: Some(PhysicalPlanType::HashJoin(Box::new(diff --git a/datafusion/src/logical_plan/builder.rs b/datafusion/src/logical_plan/builder.rsindex b6017b743e..2e69814d26 100644--- a/datafusion/src/logical_plan/builder.rs+++ b/datafusion/src/logical_plan/builder.rs@@ -347,7 +347,7 @@ fn build_join_schema(join_type: &JoinType,) -> Result<DFSchema> {let fields: Vec<DFField> = match join_type {- JoinType::Inner | JoinType::Left => {+ JoinType::Inner | JoinType::Left | JoinType::Full => {// remove right-side join keys if they have the same names as the left-sidelet duplicate_keys = &on.iter()diff --git a/datafusion/src/logical_plan/plan.rs b/datafusion/src/logical_plan/plan.rsindex 606ef1e222..13509d13eb 100644--- a/datafusion/src/logical_plan/plan.rs+++ b/datafusion/src/logical_plan/plan.rs@@ -39,12 +39,14 @@ use crate::logical_plan::dfschema::DFSchemaRef;/// Join type#[derive(Debug, Clone, Copy)]pub enum JoinType {- /// Inner join+ /// Inner JoinInner,- /// Left join+ /// Left JoinLeft,- /// Right join+ /// Right JoinRight,+ /// Full Join+ Full,}/// A LogicalPlan represents the different types of relationaldiff --git a/datafusion/src/optimizer/hash_build_probe_order.rs b/datafusion/src/optimizer/hash_build_probe_order.rsindex 086e2f0319..b27171f058 100644--- a/datafusion/src/optimizer/hash_build_probe_order.rs+++ b/datafusion/src/optimizer/hash_build_probe_order.rs@@ -203,6 +203,7 @@ impl HashBuildProbeOrder {fn swap_join_type(join_type: JoinType) -> JoinType {match join_type {JoinType::Inner => JoinType::Inner,+ JoinType::Full => JoinType::Full,JoinType::Left => JoinType::Right,JoinType::Right => JoinType::Left,}diff --git a/datafusion/src/physical_plan/hash_join.rs b/datafusion/src/physical_plan/hash_join.rsindex 60d65b2361..2682623d37 100644--- a/datafusion/src/physical_plan/hash_join.rs+++ b/datafusion/src/physical_plan/hash_join.rs@@ -180,7 +180,7 @@ impl HashJoinExec {/// Calculates column indices and left/right placement on input / output schemas and jointypefn column_indices_from_schema(&self) -> ArrowResult<Vec<ColumnIndex>> {let (primary_is_left, primary_schema, secondary_schema) = match self.join_type {- JoinType::Inner | JoinType::Left => {+ JoinType::Inner | JoinType::Left | JoinType::Full => {(true, self.left.schema(), self.right.schema())}JoinType::Right => (false, self.right.schema(), self.left.schema()),@@ -372,7 +372,7 @@ impl ExecutionPlan for HashJoinExec {let column_indices = self.column_indices_from_schema()?;let num_rows = left_data.1.num_rows();let visited_left_side = match self.join_type {- JoinType::Left => vec![false; num_rows],+ JoinType::Left | JoinType::Full => vec![false; num_rows],JoinType::Inner | JoinType::Right => vec![],};Ok(Box::pin(HashJoinStream {@@ -644,7 +644,7 @@ fn build_join_indexes(}Ok((left_indices.finish(), right_indices.finish()))}- JoinType::Right => {+ JoinType::Right | JoinType::Full => {let mut left_indices = UInt64Builder::new(0);let mut right_indices = UInt32Builder::new(0);@@ -1058,7 +1058,7 @@ impl Stream for HashJoinStream {self.num_output_rows += batch.num_rows();match self.join_type {- JoinType::Left => {+ JoinType::Left | JoinType::Full => {left_side.iter().flatten().for_each(|x| {self.visited_left_side[x as usize] = true;});@@ -1072,7 +1072,7 @@ impl Stream for HashJoinStream {let start = Instant::now();// For the left join, produce rows for unmatched rowsmatch self.join_type {- JoinType::Left if !self.is_exhausted => {+ JoinType::Left | JoinType::Full if !self.is_exhausted => {let result = produce_unmatched(&self.visited_left_side,&self.schema,@@ -1092,7 +1092,10 @@ impl Stream for HashJoinStream {self.is_exhausted = true;return Some(result);}- JoinType::Left | JoinType::Inner | JoinType::Right => {}+ JoinType::Left+ | JoinType::Full+ | JoinType::Inner+ | JoinType::Right => {}}debug!(@@ -1410,6 +1413,46 @@ mod tests {assert_batches_sorted_eq!(expected, &batches);}+ #[tokio::test]+ async fn join_full_multi_batch() {+ let left = build_table(+ ("a1", &vec![1, 2, 3]),+ ("b1", &vec![4, 5, 7]), // 7 does not exist on the right+ ("c1", &vec![7, 8, 9]),+ );+ // create two identical batches for the right side+ let right = build_table_two_batches(+ ("a2", &vec![10, 20, 30]),+ ("b2", &vec![4, 5, 6]),+ ("c2", &vec![70, 80, 90]),+ );+ let on = &[("b1", "b2")];++ let join = join(left, right, on, &JoinType::Full).unwrap();++ let columns = columns(&join.schema());+ assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);++ let stream = join.execute(0).await.unwrap();+ let batches = common::collect(stream).await.unwrap();++ let expected = vec![+ "+----+----+----+----+----+----+",+ "| a1 | b1 | c1 | a2 | b2 | c2 |",+ "+----+----+----+----+----+----+",+ "| | | | 30 | 6 | 90 |",+ "| | | | 30 | 6 | 90 |",+ "| 1 | 4 | 7 | 10 | 4 | 70 |",+ "| 1 | 4 | 7 | 10 | 4 | 70 |",+ "| 2 | 5 | 8 | 20 | 5 | 80 |",+ "| 2 | 5 | 8 | 20 | 5 | 80 |",+ "| 3 | 7 | 9 | | | |",+ "+----+----+----+----+----+----+",+ ];++ assert_batches_sorted_eq!(expected, &batches);+ }+#[tokio::test]async fn join_left_empty_right() {let left = build_table(@@ -1442,6 +1485,38 @@ mod tests {assert_batches_sorted_eq!(expected, &batches);}+ #[tokio::test]+ async fn join_full_empty_right() {+ let left = build_table(+ ("a1", &vec![1, 2, 3]),+ ("b1", &vec![4, 5, 7]),+ ("c1", &vec![7, 8, 9]),+ );+ let right = build_table_i32(("a2", &vec![]), ("b2", &vec![]), ("c2", &vec![]));+ let on = &[("b1", "b2")];+ let schema = right.schema();+ let right = Arc::new(MemoryExec::try_new(&[vec![right]], schema, None).unwrap());+ let join = join(left, right, on, &JoinType::Full).unwrap();++ let columns = columns(&join.schema());+ assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);++ let stream = join.execute(0).await.unwrap();+ let batches = common::collect(stream).await.unwrap();++ let expected = vec![+ "+----+----+----+----+----+----+",+ "| a1 | b1 | c1 | a2 | b2 | c2 |",+ "+----+----+----+----+----+----+",+ "| 1 | 4 | 7 | | | |",+ "| 2 | 5 | 8 | | | |",+ "| 3 | 7 | 9 | | | |",+ "+----+----+----+----+----+----+",+ ];++ assert_batches_sorted_eq!(expected, &batches);+ }+#[tokio::test]async fn join_left_one() -> Result<()> {let left = build_table(@@ -1515,6 +1590,43 @@ mod tests {Ok(())}+ #[tokio::test]+ async fn join_full_one() -> Result<()> {+ let left = build_table(+ ("a1", &vec![1, 2, 3]),+ ("b1", &vec![4, 5, 7]), // 7 does not exist on the right+ ("c1", &vec![7, 8, 9]),+ );+ let right = build_table(+ ("a2", &vec![10, 20, 30]),+ ("b2", &vec![4, 5, 6]),+ ("c2", &vec![70, 80, 90]),+ );+ let on = &[("b1", "b2")];++ let join = join(left, right, on, &JoinType::Full)?;++ let columns = columns(&join.schema());+ assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);++ let stream = join.execute(0).await?;+ let batches = common::collect(stream).await?;++ let expected = vec![+ "+----+----+----+----+----+----+",+ "| a1 | b1 | c1 | a2 | b2 | c2 |",+ "+----+----+----+----+----+----+",+ "| | | | 30 | 6 | 90 |",+ "| 1 | 4 | 7 | 10 | 4 | 70 |",+ "| 2 | 5 | 8 | 20 | 5 | 80 |",+ "| 3 | 7 | 9 | | | |",+ "+----+----+----+----+----+----+",+ ];+ assert_batches_sorted_eq!(expected, &batches);++ Ok(())+ }+#[test]fn join_with_hash_collision() -> Result<()> {let mut hashmap_left = HashMap::with_capacity_and_hasher(2, IdHashBuilder {});diff --git a/datafusion/src/physical_plan/hash_utils.rs b/datafusion/src/physical_plan/hash_utils.rsindex 54da1249e5..7e030af3a1 100644--- a/datafusion/src/physical_plan/hash_utils.rs+++ b/datafusion/src/physical_plan/hash_utils.rs@@ -24,12 +24,14 @@ use std::collections::HashSet;/// All valid types of joins.#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub enum JoinType {- /// Inner join+ /// Inner JoinInner,- /// Left+ /// Left JoinLeft,- /// Right+ /// Right JoinRight,+ /// Full Join+ Full,}/// The on clause of the join, as vector of (left, right) columns.@@ -92,7 +94,7 @@ pub fn build_join_schema(join_type: &JoinType,) -> Schema {let fields: Vec<Field> = match join_type {- JoinType::Inner | JoinType::Left => {+ JoinType::Inner | JoinType::Left | JoinType::Full => {// remove right-side join keys if they have the same names as the left-sidelet duplicate_keys = &on.iter()diff --git a/datafusion/src/physical_plan/planner.rs b/datafusion/src/physical_plan/planner.rsindex ae6ad5075d..acbb863c60 100644--- a/datafusion/src/physical_plan/planner.rs+++ b/datafusion/src/physical_plan/planner.rs@@ -298,6 +298,7 @@ impl DefaultPhysicalPlanner {JoinType::Inner => hash_utils::JoinType::Inner,JoinType::Left => hash_utils::JoinType::Left,JoinType::Right => hash_utils::JoinType::Right,+ JoinType::Full => hash_utils::JoinType::Full,};if ctx_state.config.concurrency > 1 && ctx_state.config.repartition_joins{diff --git a/datafusion/src/sql/planner.rs b/datafusion/src/sql/planner.rsindex d5aae24e79..036c66da16 100644--- a/datafusion/src/sql/planner.rs+++ b/datafusion/src/sql/planner.rs@@ -355,6 +355,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {JoinOperator::Inner(constraint) => {self.parse_join(left, &right, constraint, JoinType::Inner)}+ JoinOperator::FullOuter(constraint) => {+ self.parse_join(left, &right, constraint, JoinType::Full)+ }JoinOperator::CrossJoin => self.parse_cross_join(left, &right),other => Err(DataFusionError::NotImplemented(format!("Unsupported JOIN operator {:?}",diff --git a/datafusion/tests/sql.rs b/datafusion/tests/sql.rsindex 5c90f8ac16..45a5694fc8 100644--- a/datafusion/tests/sql.rs+++ b/datafusion/tests/sql.rs@@ -1329,6 +1329,27 @@ async fn right_join() -> Result<()> {Ok(())}+#[tokio::test]+async fn full_join() -> Result<()> {+ let mut ctx = create_join_context("t1_id", "t2_id")?;+ let sql = "SELECT t1_id, t1_name, t2_name FROM t1 FULL JOIN t2 ON t1_id = t2_id ORDER BY t1_id";+ let actual = execute(&mut ctx, sql).await;+ let expected = vec![+ vec!["NULL", "NULL", "w"],+ vec!["11", "a", "z"],+ vec!["22", "b", "y"],+ vec!["33", "c", "NULL"],+ vec!["44", "d", "x"],+ ];+ assert_eq!(expected, actual);++ let sql = "SELECT t1_id, t1_name, t2_name FROM t1 FULL OUTER JOIN t2 ON t1_id = t2_id ORDER BY t1_id";+ let actual = execute(&mut ctx, sql).await;+ assert_eq!(expected, actual);++ Ok(())+}+#[tokio::test]async fn left_join_using() -> Result<()> {let mut ctx = create_join_context("id", "id")?;