datafusion_common/join_type.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Defines the [`JoinType`], [`JoinConstraint`] and [`JoinSide`] types.
6
7use std::{
8 fmt::{self, Display, Formatter},
9 str::FromStr,
10};
11
12use crate::error::_not_impl_err;
13use crate::{DataFusionError, Result};
14
15/// Join type
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)]
17pub enum JoinType {
18 /// Inner Join - Returns only rows where there is a matching value in both tables based on the join condition.
19 /// For example, if joining table A and B on A.id = B.id, only rows where A.id equals B.id will be included.
20 /// All columns from both tables are returned for the matching rows. Non-matching rows are excluded entirely.
21 Inner,
22 /// Left Join - Returns all rows from the left table and matching rows from the right table.
23 /// If no match, NULL values are returned for columns from the right table.
24 Left,
25 /// Right Join - Returns all rows from the right table and matching rows from the left table.
26 /// If no match, NULL values are returned for columns from the left table.
27 Right,
28 /// Full Join (also called Full Outer Join) - Returns all rows from both tables, matching rows where possible.
29 /// When a row from either table has no match in the other table, the missing columns are filled with NULL values.
30 /// For example, if table A has row X with no match in table B, the result will contain row X with NULL values for all of table B's columns.
31 /// This join type preserves all records from both tables, making it useful when you need to see all data regardless of matches.
32 Full,
33 /// Left Semi Join - Returns rows from the left table that have matching rows in the right table.
34 /// Only columns from the left table are returned.
35 LeftSemi,
36 /// Right Semi Join - Returns rows from the right table that have matching rows in the left table.
37 /// Only columns from the right table are returned.
38 RightSemi,
39 /// Left Anti Join - Returns rows from the left table that do not have a matching row in the right table.
40 LeftAnti,
41 /// Right Anti Join - Returns rows from the right table that do not have a matching row in the left table.
42 RightAnti,
43 /// Left Mark join
44 ///
45 /// Returns one record for each record from the left input. The output contains an additional
46 /// column "mark" which is true if there is at least one match in the right input where the
47 /// join condition evaluates to true. Otherwise, the mark column is false. For more details see
48 /// [1]. This join type is used to decorrelate EXISTS subqueries used inside disjunctive
49 /// predicates.
50 ///
51 /// For scalar `NOT IN`, DataFusion can plan a null-aware hash mark join where the
52 /// mark column is nullable: TRUE for a match, NULL for SQL UNKNOWN, and FALSE
53 /// otherwise. Row-valued multi-column `NOT IN` and non-hash residual predicate
54 /// null-aware mark semantics are not implemented.
55 ///
56 /// [1]: http://btw2017.informatik.uni-stuttgart.de/slidesandpapers/F1-10-37/paper_web.pdf
57 LeftMark,
58 /// Right Mark Join
59 ///
60 /// Same logic as the LeftMark Join above, however it returns a record for each record from the
61 /// right input.
62 RightMark,
63}
64
65impl JoinType {
66 pub fn is_outer(self) -> bool {
67 self == JoinType::Left || self == JoinType::Right || self == JoinType::Full
68 }
69
70 /// Returns the `JoinType` if the (2) inputs were swapped
71 ///
72 /// Panics if [`Self::supports_swap`] returns false
73 pub fn swap(&self) -> JoinType {
74 match self {
75 JoinType::Inner => JoinType::Inner,
76 JoinType::Full => JoinType::Full,
77 JoinType::Left => JoinType::Right,
78 JoinType::Right => JoinType::Left,
79 JoinType::LeftSemi => JoinType::RightSemi,
80 JoinType::RightSemi => JoinType::LeftSemi,
81 JoinType::LeftAnti => JoinType::RightAnti,
82 JoinType::RightAnti => JoinType::LeftAnti,
83 JoinType::LeftMark => JoinType::RightMark,
84 JoinType::RightMark => JoinType::LeftMark,
85 }
86 }
87
88 /// Whether each side of the join is preserved for ON-clause filter pushdown.
89 ///
90 /// It is only correct to push ON-clause filters below a join for preserved
91 /// inputs.
92 ///
93 /// # "Preserved" input definition
94 ///
95 /// A join side is preserved if the join returns all or a subset of the rows
96 /// from that side, such that each output row directly maps to an input row.
97 /// If a side is not preserved, the join can produce extra null rows that
98 /// don't map to any input row.
99 ///
100 /// # Return Value
101 ///
102 /// A tuple of booleans - (left_preserved, right_preserved).
103 pub fn on_lr_is_preserved(&self) -> (bool, bool) {
104 match self {
105 JoinType::Inner => (true, true),
106 JoinType::Left => (false, true),
107 JoinType::Right => (true, false),
108 JoinType::Full => (false, false),
109 JoinType::LeftSemi | JoinType::RightSemi => (true, true),
110 JoinType::LeftAnti => (false, true),
111 JoinType::RightAnti => (true, false),
112 JoinType::LeftMark => (false, true),
113 JoinType::RightMark => (true, false),
114 }
115 }
116
117 /// Does the join type support swapping inputs?
118 pub fn supports_swap(&self) -> bool {
119 matches!(
120 self,
121 JoinType::Inner
122 | JoinType::Left
123 | JoinType::Right
124 | JoinType::Full
125 | JoinType::LeftSemi
126 | JoinType::RightSemi
127 | JoinType::LeftAnti
128 | JoinType::RightAnti
129 | JoinType::LeftMark
130 | JoinType::RightMark
131 )
132 }
133
134 /// Returns true when an empty build side necessarily produces an empty
135 /// result for this join type.
136 pub fn empty_build_side_produces_empty_result(self) -> bool {
137 matches!(
138 self,
139 JoinType::Inner
140 | JoinType::Left
141 | JoinType::LeftSemi
142 | JoinType::LeftAnti
143 | JoinType::LeftMark
144 | JoinType::RightSemi
145 )
146 }
147
148 /// Returns true when an empty build-side map necessarily produces an empty
149 /// result for this join type, even if the build side still contains rows.
150 ///
151 /// Every output row of these join types requires a matching build row, so
152 /// when the map has no matchable keys the result is empty regardless of the
153 /// probe side. Note this is a subset of
154 /// [`Self::empty_build_side_produces_empty_result`]: an empty build side
155 /// yields an empty map, but the map can also be empty when every build row
156 /// has a NULL join key under [`NullEquality::NullEqualsNothing`].
157 ///
158 /// [`NullEquality::NullEqualsNothing`]: crate::NullEquality::NullEqualsNothing
159 pub fn empty_map_produces_empty_result(self) -> bool {
160 matches!(
161 self,
162 JoinType::Inner | JoinType::LeftSemi | JoinType::RightSemi
163 )
164 }
165}
166
167impl Display for JoinType {
168 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
169 let join_type = match self {
170 JoinType::Inner => "Inner",
171 JoinType::Left => "Left",
172 JoinType::Right => "Right",
173 JoinType::Full => "Full",
174 JoinType::LeftSemi => "LeftSemi",
175 JoinType::RightSemi => "RightSemi",
176 JoinType::LeftAnti => "LeftAnti",
177 JoinType::RightAnti => "RightAnti",
178 JoinType::LeftMark => "LeftMark",
179 JoinType::RightMark => "RightMark",
180 };
181 write!(f, "{join_type}")
182 }
183}
184
185impl FromStr for JoinType {
186 type Err = DataFusionError;
187
188 fn from_str(s: &str) -> Result<Self> {
189 let s = s.to_uppercase();
190 match s.as_str() {
191 "INNER" => Ok(JoinType::Inner),
192 "LEFT" => Ok(JoinType::Left),
193 "RIGHT" => Ok(JoinType::Right),
194 "FULL" => Ok(JoinType::Full),
195 "LEFTSEMI" => Ok(JoinType::LeftSemi),
196 "RIGHTSEMI" => Ok(JoinType::RightSemi),
197 "LEFTANTI" => Ok(JoinType::LeftAnti),
198 "RIGHTANTI" => Ok(JoinType::RightAnti),
199 "LEFTMARK" => Ok(JoinType::LeftMark),
200 "RIGHTMARK" => Ok(JoinType::RightMark),
201 _ => _not_impl_err!("The join type {s} does not exist or is not implemented"),
202 }
203 }
204}
205
206/// Join constraint
207#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)]
208pub enum JoinConstraint {
209 /// Join ON
210 On,
211 /// Join USING
212 Using,
213}
214
215impl Display for JoinSide {
216 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
217 match self {
218 JoinSide::Left => write!(f, "left"),
219 JoinSide::Right => write!(f, "right"),
220 JoinSide::None => write!(f, "none"),
221 }
222 }
223}
224
225/// Join side.
226/// Stores the referred table side during calculations
227#[derive(Debug, Clone, Copy, PartialEq)]
228pub enum JoinSide {
229 /// Left side of the join
230 Left,
231 /// Right side of the join
232 Right,
233 /// Neither side of the join, used for Mark joins where the mark column does not belong to
234 /// either side of the join
235 None,
236}
237
238impl JoinSide {
239 /// Inverse the join side
240 pub fn negate(&self) -> Self {
241 match self {
242 JoinSide::Left => JoinSide::Right,
243 JoinSide::Right => JoinSide::Left,
244 JoinSide::None => JoinSide::None,
245 }
246 }
247}