Skip to content

Commit 1deeaf9

Browse files
[FEAT]: sql cross join (#3110)
still todo: - [x] add tests ## Notes for reviewers: This does not actually implement a physical cross join, but just implements the logical cross join as well as cross join to inner join optimization `eliminate_cross_join.rs` This treats an inner join with no join conditions as cross join. (inspired by a recent [change in datafusion](apache/datafusion#12985)). If the cross join can not be optimized away, an error will be raised when attempting to execute the plan.
1 parent 5228930 commit 1deeaf9

11 files changed

Lines changed: 984 additions & 12 deletions

File tree

src/common/error/src/error.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,14 @@ pub enum DaftError {
4646
FmtError(#[from] std::fmt::Error),
4747
#[error("DaftError::RegexError {0}")]
4848
RegexError(#[from] regex::Error),
49+
#[error("Not Yet Implemented: {0}")]
50+
NotImplemented(String),
51+
}
52+
53+
impl DaftError {
54+
pub fn not_implemented<T: std::fmt::Display>(msg: T) -> Self {
55+
Self::NotImplemented(msg.to_string())
56+
}
4957
}
5058

5159
impl From<arrow2::error::Error> for DaftError {

src/daft-physical-plan/src/translate.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
use common_error::DaftResult;
1+
use common_error::{DaftError, DaftResult};
22
use daft_core::{join::JoinStrategy, prelude::Schema};
33
use daft_dsl::ExprRef;
4-
use daft_plan::{LogicalPlan, LogicalPlanRef, SourceInfo};
4+
use daft_plan::{JoinType, LogicalPlan, LogicalPlanRef, SourceInfo};
55

66
use crate::local_plan::{LocalPhysicalPlan, LocalPhysicalPlanRef};
77

@@ -119,8 +119,18 @@ pub fn translate(plan: &LogicalPlanRef) -> DaftResult<LocalPhysicalPlanRef> {
119119
))
120120
}
121121
LogicalPlan::Join(join) => {
122+
if join.left_on.is_empty()
123+
&& join.right_on.is_empty()
124+
&& join.join_type == JoinType::Inner
125+
{
126+
return Err(DaftError::not_implemented(
127+
"Joins without join conditions (cross join) are not supported yet",
128+
));
129+
}
122130
if join.join_strategy.is_some_and(|x| x != JoinStrategy::Hash) {
123-
todo!("Only hash join is supported for now")
131+
return Err(DaftError::not_implemented(
132+
"Only hash join is supported for now",
133+
));
124134
}
125135
let left = translate(&join.left)?;
126136
let right = translate(&join.right)?;

src/daft-plan/src/builder.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,13 @@ impl From<&LogicalPlanBuilder> for LogicalPlanRef {
8484
value.plan.clone()
8585
}
8686
}
87+
88+
impl From<LogicalPlanRef> for LogicalPlanBuilder {
89+
fn from(plan: LogicalPlanRef) -> Self {
90+
Self::new(plan, None)
91+
}
92+
}
93+
8794
pub trait IntoGlobPath {
8895
fn into_glob_path(self) -> Vec<String>;
8996
}
@@ -468,6 +475,23 @@ impl LogicalPlanBuilder {
468475
Ok(self.with_new_plan(logical_plan))
469476
}
470477

478+
pub fn cross_join<Right: Into<LogicalPlanRef>>(
479+
&self,
480+
right: Right,
481+
join_suffix: Option<&str>,
482+
join_prefix: Option<&str>,
483+
) -> DaftResult<Self> {
484+
self.join(
485+
right,
486+
vec![],
487+
vec![],
488+
JoinType::Inner,
489+
None,
490+
join_suffix,
491+
join_prefix,
492+
)
493+
}
494+
471495
pub fn concat(&self, other: &Self) -> DaftResult<Self> {
472496
let logical_plan: LogicalPlan =
473497
logical_ops::Concat::try_new(self.plan.clone(), other.plan.clone())?.into();

src/daft-plan/src/logical_ops/project.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ impl Project {
3737
projected_schema,
3838
})
3939
}
40+
/// Create a new Projection using the specified output schema
41+
pub(crate) fn new_from_schema(input: Arc<LogicalPlan>, schema: SchemaRef) -> Result<Self> {
42+
let expr: Vec<ExprRef> = schema
43+
.names()
44+
.into_iter()
45+
.map(|n| Arc::new(Expr::Column(Arc::from(n))))
46+
.collect();
47+
Self::try_new(input, expr)
48+
}
4049

4150
pub fn multiline_display(&self) -> Vec<String> {
4251
vec![format!(
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
// Borrowed from DataFusion project: datafusion/optimizer/src/join_key_set.rs
2+
3+
// Licensed to the Apache Software Foundation (ASF) under one
4+
// or more contributor license agreements. See the NOTICE file
5+
// distributed with this work for additional information
6+
// regarding copyright ownership. The ASF licenses this file
7+
// to you under the Apache License, Version 2.0 (the
8+
// "License"); you may not use this file except in compliance
9+
// with the License. You may obtain a copy of the License at
10+
//
11+
// http://www.apache.org/licenses/LICENSE-2.0
12+
//
13+
// Unless required by applicable law or agreed to in writing,
14+
// software distributed under the License is distributed on an
15+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16+
// KIND, either express or implied. See the License for the
17+
// specific language governing permissions and limitations
18+
// under the License.
19+
20+
//! [JoinKeySet] for tracking the set of join keys in a plan.
21+
22+
use std::sync::Arc;
23+
24+
use daft_dsl::{Expr, ExprRef};
25+
use indexmap::{Equivalent, IndexSet};
26+
27+
/// Tracks a set of equality Join keys
28+
///
29+
/// A join key is an expression that is used to join two tables via an equality
30+
/// predicate such as `a.x = b.y`
31+
///
32+
/// This struct models `a.x + 5 = b.y AND a.z = b.z` as two join keys
33+
/// 1. `(a.x + 5, b.y)`
34+
/// 2. `(a.z, b.z)`
35+
///
36+
/// # Important properties:
37+
///
38+
/// 1. Retains insert order
39+
/// 2. Can quickly look up if a pair of expressions are in the set.
40+
#[derive(Debug)]
41+
pub struct JoinKeySet {
42+
inner: IndexSet<(ExprRef, ExprRef)>,
43+
}
44+
45+
impl JoinKeySet {
46+
/// Create a new empty set
47+
pub fn new() -> Self {
48+
Self {
49+
inner: IndexSet::new(),
50+
}
51+
}
52+
53+
/// Return true if the set contains a join pair
54+
/// where left = right or right = left
55+
pub fn contains(&self, left: &Expr, right: &Expr) -> bool {
56+
self.inner.contains(&ExprPair::new(left, right))
57+
|| self.inner.contains(&ExprPair::new(right, left))
58+
}
59+
60+
/// Insert the join key `(left = right)` into the set if join pair `(right =
61+
/// left)` is not already in the set
62+
///
63+
/// returns true if the pair was inserted
64+
pub fn insert(&mut self, left: &Expr, right: &Expr) -> bool {
65+
if self.contains(left, right) {
66+
false
67+
} else {
68+
self.inner
69+
.insert((left.clone().arced(), right.clone().arced()));
70+
true
71+
}
72+
}
73+
74+
/// Same as [`Self::insert`] but avoids cloning expression if they
75+
/// are owned
76+
pub fn insert_owned(&mut self, left: Expr, right: Expr) -> bool {
77+
if self.contains(&left, &right) {
78+
false
79+
} else {
80+
self.inner.insert((Arc::new(left), Arc::new(right)));
81+
true
82+
}
83+
}
84+
85+
/// Inserts potentially many join keys into the set, copying only when necessary
86+
///
87+
/// returns true if any of the pairs were inserted
88+
pub fn insert_all<'a>(
89+
&mut self,
90+
iter: impl IntoIterator<Item = &'a (ExprRef, ExprRef)>,
91+
) -> bool {
92+
let mut inserted = false;
93+
for (left, right) in iter {
94+
inserted |= self.insert(left, right);
95+
}
96+
inserted
97+
}
98+
99+
/// Same as [`Self::insert_all`] but avoids cloning expressions if they are
100+
/// already owned
101+
///
102+
/// returns true if any of the pairs were inserted
103+
pub fn insert_all_owned(&mut self, iter: impl IntoIterator<Item = (ExprRef, ExprRef)>) -> bool {
104+
let mut inserted = false;
105+
for (left, right) in iter {
106+
inserted |= self.insert_owned(Arc::unwrap_or_clone(left), Arc::unwrap_or_clone(right));
107+
}
108+
inserted
109+
}
110+
111+
/// Inserts any join keys that are common to both `s1` and `s2` into self
112+
pub fn insert_intersection(&mut self, s1: &Self, s2: &Self) {
113+
// note can't use inner.intersection as we need to consider both (l, r)
114+
// and (r, l) in equality
115+
for (left, right) in &s1.inner {
116+
if s2.contains(left.as_ref(), right.as_ref()) {
117+
self.insert(left.as_ref(), right.as_ref());
118+
}
119+
}
120+
}
121+
122+
/// returns true if this set is empty
123+
pub fn is_empty(&self) -> bool {
124+
self.inner.is_empty()
125+
}
126+
127+
/// Return the length of this set
128+
#[cfg(test)]
129+
pub fn len(&self) -> usize {
130+
self.inner.len()
131+
}
132+
133+
/// Return an iterator over the join keys in this set
134+
pub fn iter(&self) -> impl Iterator<Item = (&ExprRef, &ExprRef)> {
135+
self.inner.iter().map(|(l, r)| (l, r))
136+
}
137+
}
138+
139+
/// Custom comparison operation to avoid copying owned values
140+
///
141+
/// This behaves like a `(Expr, Expr)` tuple for hashing and comparison, but
142+
/// avoids copying the values simply to comparing them.
143+
#[derive(Debug, Eq, PartialEq, Hash)]
144+
struct ExprPair<'a>(&'a Expr, &'a Expr);
145+
146+
impl<'a> ExprPair<'a> {
147+
fn new(left: &'a Expr, right: &'a Expr) -> Self {
148+
Self(left, right)
149+
}
150+
}
151+
152+
impl<'a> Equivalent<(ExprRef, ExprRef)> for ExprPair<'a> {
153+
fn equivalent(&self, other: &(ExprRef, ExprRef)) -> bool {
154+
self.0 == other.0.as_ref() && self.1 == other.1.as_ref()
155+
}
156+
}

src/daft-plan/src/logical_optimization/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub(crate) mod join_key_set;
12
mod logical_plan_tracker;
23
mod optimizer;
34
mod rules;

src/daft-plan/src/logical_optimization/optimizer.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use common_treenode::Transformed;
66
use super::{
77
logical_plan_tracker::LogicalPlanTracker,
88
rules::{
9-
DropRepartition, OptimizerRule, PushDownFilter, PushDownLimit, PushDownProjection,
10-
SplitActorPoolProjects,
9+
DropRepartition, EliminateCrossJoin, OptimizerRule, PushDownFilter, PushDownLimit,
10+
PushDownProjection, SplitActorPoolProjects,
1111
},
1212
};
1313
use crate::LogicalPlan;
@@ -112,6 +112,7 @@ impl Optimizer {
112112
Box::new(DropRepartition::new()),
113113
Box::new(PushDownFilter::new()),
114114
Box::new(PushDownProjection::new()),
115+
Box::new(EliminateCrossJoin::new()),
115116
],
116117
// Use a fixed-point policy for the pushdown rules: PushDownProjection can produce a Filter node
117118
// at the current node, which would require another batch application in order to have a chance to push

0 commit comments

Comments
 (0)