Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Improve subquery support #110

Draft
wants to merge 1 commit into
base: cubesql-3-04-2022
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion datafusion-cli/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion datafusion/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@ cranelift-module = { version = "0.82.0", optional = true }
ordered-float = "2.10"
parquet = { git = 'https://github.com/cube-js/arrow-rs.git', rev = "096ef28dde6b1ae43ce89ba2c3a9d98295f2972e", features = ["arrow"], optional = true }
pyo3 = { version = "0.16", optional = true }
sqlparser = { git = 'https://github.com/cube-js/sqlparser-rs.git', rev = "b3b40586d4c32a218ffdfcb0462e7e216cf3d6eb" }
sqlparser = { git = 'https://github.com/cube-js/sqlparser-rs.git', rev = "2229652dc8fae8f45cbec344b4a1e40cf1bb69d9" }
2 changes: 1 addition & 1 deletion datafusion/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pin-project-lite= "^0.2.7"
pyo3 = { version = "0.16", optional = true }
rand = "0.8"
smallvec = { version = "1.6", features = ["union"] }
sqlparser = { git = 'https://github.com/cube-js/sqlparser-rs.git', rev = "b3b40586d4c32a218ffdfcb0462e7e216cf3d6eb" }
sqlparser = { git = 'https://github.com/cube-js/sqlparser-rs.git', rev = "2229652dc8fae8f45cbec344b4a1e40cf1bb69d9" }
tempfile = "3"
tokio = { version = "1.0", features = ["macros", "rt", "rt-multi-thread", "sync", "fs", "parking_lot"] }
tokio-stream = "0.1"
Expand Down
1 change: 1 addition & 0 deletions datafusion/core/src/datasource/listing/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ impl ExpressionVisitor for ApplicabilityVisitor<'_> {
| Expr::ILike { .. }
| Expr::SimilarTo { .. }
| Expr::InList { .. }
| Expr::InSubquery { .. }
| Expr::GetIndexedField { .. }
| Expr::Case { .. } => Recursion::Continue(self),

Expand Down
7 changes: 5 additions & 2 deletions datafusion/core/src/logical_plan/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::error::{DataFusionError, Result};
use crate::logical_plan::expr_schema::ExprSchemable;
use crate::logical_plan::plan::{
Aggregate, Analyze, EmptyRelation, Explain, Filter, Join, Projection, Sort, Subquery,
TableScan, TableUDFs, ToStringifiedPlan, Union, Window,
SubqueryType, TableScan, TableUDFs, ToStringifiedPlan, Union, Window,
};
use crate::optimizer::utils;
use crate::prelude::*;
Expand Down Expand Up @@ -528,12 +528,15 @@ impl LogicalPlanBuilder {
pub fn subquery(
&self,
subqueries: impl IntoIterator<Item = impl Into<LogicalPlan>>,
types: impl IntoIterator<Item = SubqueryType>,
) -> Result<Self> {
let subqueries = subqueries.into_iter().map(|l| l.into()).collect::<Vec<_>>();
let schema = Arc::new(Subquery::merged_schema(&self.plan, &subqueries));
let types = types.into_iter().collect::<Vec<_>>();
let schema = Arc::new(Subquery::merged_schema(&self.plan, &subqueries, &types));
Ok(Self::from(LogicalPlan::Subquery(Subquery {
input: Arc::new(self.plan.clone()),
subqueries,
types,
schema,
})))
}
Expand Down
17 changes: 16 additions & 1 deletion datafusion/core/src/logical_plan/expr_rewriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,16 @@ impl ExprRewritable for Expr {
op,
right: rewrite_boxed(right, rewriter)?,
},
Expr::AnyExpr { left, op, right } => Expr::AnyExpr {
Expr::AnyExpr {
left,
op,
right,
all,
} => Expr::AnyExpr {
left: rewrite_boxed(left, rewriter)?,
op,
right: rewrite_boxed(right, rewriter)?,
all,
},
Expr::Like(Like {
negated,
Expand Down Expand Up @@ -263,6 +269,15 @@ impl ExprRewritable for Expr {
list: rewrite_vec(list, rewriter)?,
negated,
},
Expr::InSubquery {
expr,
subquery,
negated,
} => Expr::InSubquery {
expr: rewrite_boxed(expr, rewriter)?,
subquery: rewrite_boxed(subquery, rewriter)?,
negated,
},
Expr::Wildcard => Expr::Wildcard,
Expr::QualifiedWildcard { qualifier } => {
Expr::QualifiedWildcard { qualifier }
Expand Down
3 changes: 2 additions & 1 deletion datafusion/core/src/logical_plan/expr_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ impl ExprSchemable for Expr {
| Expr::IsNull(_)
| Expr::Between { .. }
| Expr::InList { .. }
| Expr::InSubquery { .. }
| Expr::AnyExpr { .. }
| Expr::IsNotNull(_) => Ok(DataType::Boolean),
Expr::BinaryExpr {
Expand Down Expand Up @@ -158,7 +159,7 @@ impl ExprSchemable for Expr {
| Expr::Between { expr, .. }
| Expr::InList { expr, .. } => expr.nullable(input_schema),
Expr::Column(c) => input_schema.nullable(c),
Expr::OuterColumn(_, _) => Ok(true),
Expr::OuterColumn(_, _) | Expr::InSubquery { .. } => Ok(true),
Expr::Literal(value) => Ok(value.is_null()),
Expr::Case {
when_then_expr,
Expand Down
4 changes: 4 additions & 0 deletions datafusion/core/src/logical_plan/expr_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,10 @@ impl ExprVisitable for Expr {
list.iter()
.try_fold(visitor, |visitor, arg| arg.accept(visitor))
}
Expr::InSubquery { expr, subquery, .. } => {
let visitor = expr.accept(visitor)?;
subquery.accept(visitor)
}
}?;

visitor.post_visit(self)
Expand Down
2 changes: 1 addition & 1 deletion datafusion/core/src/logical_plan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,6 @@ pub use plan::{
CreateCatalogSchema, CreateExternalTable, CreateMemoryTable, CrossJoin, Distinct,
DropTable, EmptyRelation, Filter, JoinConstraint, JoinType, Limit, LogicalPlan,
Partitioning, PlanType, PlanVisitor, Repartition, StringifiedPlan, Subquery,
TableScan, ToStringifiedPlan, Union, Values,
SubqueryType, TableScan, ToStringifiedPlan, Union, Values,
};
pub use registry::FunctionRegistry;
109 changes: 98 additions & 11 deletions datafusion/core/src/logical_plan/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::error::DataFusionError;
use crate::logical_plan::dfschema::DFSchemaRef;
use crate::sql::parser::FileType;
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion_common::DFSchema;
use datafusion_common::{DFField, DFSchema};
use std::fmt::Formatter;
use std::{
collections::HashSet,
Expand Down Expand Up @@ -267,22 +267,97 @@ pub struct Limit {
/// Evaluates correlated sub queries
#[derive(Clone)]
pub struct Subquery {
/// The list of sub queries
pub subqueries: Vec<LogicalPlan>,
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
/// The list of sub queries
pub subqueries: Vec<LogicalPlan>,
/// The list of subquery types
pub types: Vec<SubqueryType>,
/// The schema description of the output
pub schema: DFSchemaRef,
}

/// Subquery type
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub enum SubqueryType {
/// Scalar (SELECT, WHERE) evaluating to one value
Scalar,
/// EXISTS(...) evaluating to true if at least one row was produced
Exists,
/// ANY(...) / ALL(...)
AnyAll,
// [NOT] IN(...) is not defined as it is implicitly evaluated as ANY = (...) / ALL <> (...)
}

impl Subquery {
/// Merge schema of main input and correlated subquery columns
pub fn merged_schema(input: &LogicalPlan, subqueries: &[LogicalPlan]) -> DFSchema {
subqueries.iter().fold((**input.schema()).clone(), |a, b| {
let mut res = a;
res.merge(b.schema());
res
})
pub fn merged_schema(
input: &LogicalPlan,
subqueries: &[LogicalPlan],
types: &[SubqueryType],
) -> DFSchema {
subqueries.iter().zip(types.iter()).fold(
(**input.schema()).clone(),
|schema, (plan, typ)| {
let mut schema = schema;
schema.merge(&Self::transform_dfschema(plan.schema(), *typ));
schema
},
)
}

/// Transform DataFusion schema according to subquery type
pub fn transform_dfschema(schema: &DFSchema, typ: SubqueryType) -> DFSchema {
match typ {
SubqueryType::Scalar => schema.clone(),
SubqueryType::Exists | SubqueryType::AnyAll => {
let new_fields = schema
.fields()
.iter()
.map(|field| {
let new_field = Subquery::transform_field(field.field(), typ);
if let Some(qualifier) = field.qualifier() {
DFField::from_qualified(qualifier, new_field)
} else {
DFField::from(new_field)
}
})
.collect();
DFSchema::new_with_metadata(new_fields, schema.metadata().clone())
.unwrap()
}
}
}

/// Transform Arrow field according to subquery type
pub fn transform_field(field: &Field, typ: SubqueryType) -> Field {
match typ {
SubqueryType::Scalar => field.clone(),
SubqueryType::Exists => Field::new(field.name(), DataType::Boolean, false),
// ANY/ALL subquery converts subquery result rows into a list
// and uses existing code evaluating ANY with a list to evaluate the result
SubqueryType::AnyAll => {
let item = Field::new_dict(
"item",
field.data_type().clone(),
true,
field.dict_id().unwrap_or(0),
field.dict_is_ordered().unwrap_or(false),
);
Field::new(field.name(), DataType::List(Box::new(item)), false)
}
}
}
}

impl Display for SubqueryType {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Scalar => "Scalar",
Self::Exists => "Exists",
Self::AnyAll => "AnyAll",
};
write!(f, "{}", name)
}
}

Expand Down Expand Up @@ -475,13 +550,23 @@ impl LogicalPlan {
LogicalPlan::Values(Values { schema, .. }) => vec![schema],
LogicalPlan::Window(Window { input, schema, .. })
| LogicalPlan::Projection(Projection { input, schema, .. })
| LogicalPlan::Subquery(Subquery { input, schema, .. })
| LogicalPlan::Aggregate(Aggregate { input, schema, .. })
| LogicalPlan::TableUDFs(TableUDFs { input, schema, .. }) => {
let mut schemas = input.all_schemas();
schemas.insert(0, schema);
schemas
}
LogicalPlan::Subquery(Subquery {
input,
subqueries,
schema,
..
}) => {
let mut schemas = input.all_schemas();
schemas.extend(subqueries.iter().map(|s| s.schema()));
schemas.insert(0, schema);
schemas
}
LogicalPlan::Join(Join {
left,
right,
Expand Down Expand Up @@ -1063,7 +1148,9 @@ impl LogicalPlan {
}
Ok(())
}
LogicalPlan::Subquery(Subquery { .. }) => write!(f, "Subquery"),
LogicalPlan::Subquery(Subquery { types, .. }) => {
write!(f, "Subquery: types={:?}", types)
}
LogicalPlan::Filter(Filter {
predicate: ref expr,
..
Expand Down
4 changes: 4 additions & 0 deletions datafusion/core/src/optimizer/common_subexpr_eliminate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,10 @@ impl ExprIdentifierVisitor<'_> {
desc.push_str("InList-");
desc.push_str(&negated.to_string());
}
Expr::InSubquery { negated, .. } => {
desc.push_str("InSubquery-");
desc.push_str(&negated.to_string());
}
Expr::Wildcard => {
desc.push_str("Wildcard-");
}
Expand Down
2 changes: 2 additions & 0 deletions datafusion/core/src/optimizer/projection_drop_out.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ fn optimize_plan(
LogicalPlan::Subquery(Subquery {
input,
subqueries,
types,
schema,
}) => {
// TODO: subqueries are not optimized
Expand All @@ -269,6 +270,7 @@ fn optimize_plan(
.map(|(p, _)| p)?,
),
subqueries: subqueries.clone(),
types: types.clone(),
schema: schema.clone(),
}),
None,
Expand Down
10 changes: 7 additions & 3 deletions datafusion/core/src/optimizer/projection_push_down.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,10 @@ fn optimize_plan(
}))
}
LogicalPlan::Subquery(Subquery {
input, subqueries, ..
input,
subqueries,
types,
..
}) => {
let mut subquery_required_columns = HashSet::new();
for subquery in subqueries.iter() {
Expand Down Expand Up @@ -484,11 +487,12 @@ fn optimize_plan(
has_projection,
_optimizer_config,
)?;
let new_schema = Subquery::merged_schema(&input, subqueries);
let new_schema = Subquery::merged_schema(&input, subqueries, types);
Ok(LogicalPlan::Subquery(Subquery {
input: Arc::new(input),
schema: Arc::new(new_schema),
subqueries: subqueries.clone(),
types: types.clone(),
schema: Arc::new(new_schema),
}))
}
// all other nodes: Add any additional columns used by
Expand Down
1 change: 1 addition & 0 deletions datafusion/core/src/optimizer/simplify_expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ impl<'a> ConstEvaluator<'a> {
| Expr::OuterColumn(_, _)
| Expr::WindowFunction { .. }
| Expr::Sort { .. }
| Expr::InSubquery { .. }
| Expr::Wildcard
| Expr::QualifiedWildcard { .. } => false,
Expr::ScalarFunction { fun, .. } => Self::volatility_ok(fun.volatility()),
Expand Down
Loading