Skip to content

Apache DataFusion SQL Query Engine

Enforce ambiguity check whilst normalizing columns (#5509)

Jeffreyaeb593f71950
diff --git a/datafusion/common/src/column.rs b/datafusion/common/src/column.rs
index ee1304ea05..4a0e392f6e 100644
--- a/datafusion/common/src/column.rs
+++ b/datafusion/common/src/column.rs
@@ -102,6 +102,10 @@ impl Column {
/// In this case, both `t1.id` and `t2.id` will match unqualified column `id`. To express this possibility, use
/// `using_columns`. Each entry in this array is a set of columns that are bound together via a `USING` clause. So
/// in this example this would be `[{t1.id, t2.id}]`.
+ #[deprecated(
+ since = "20.0.0",
+ note = "use normalize_with_schemas_and_ambiguity_check instead"
+ )]
pub fn normalize_with_schemas(
self,
schemas: &[&Arc<DFSchema>],
@@ -154,6 +158,105 @@ impl Column {
.collect(),
}))
}
+
+ /// Qualify column if not done yet.
+ ///
+ /// If this column already has a [relation](Self::relation), it will be returned as is and the given parameters are
+ /// ignored. Otherwise this will search through the given schemas to find the column.
+ ///
+ /// Will check for ambiguity at each level of `schemas`.
+ ///
+ /// A schema matches if there is a single column that -- when unqualified -- matches this column. There is an
+ /// exception for `USING` statements, see below.
+ ///
+ /// # Using columns
+ /// Take the following SQL statement:
+ ///
+ /// ```sql
+ /// SELECT id FROM t1 JOIN t2 USING(id)
+ /// ```
+ ///
+ /// In this case, both `t1.id` and `t2.id` will match unqualified column `id`. To express this possibility, use
+ /// `using_columns`. Each entry in this array is a set of columns that are bound together via a `USING` clause. So
+ /// in this example this would be `[{t1.id, t2.id}]`.
+ ///
+ /// Regarding ambiguity check, `schemas` is structured to allow levels of schemas to be passed in.
+ /// For example:
+ ///
+ /// ```text
+ /// schemas = &[
+ /// &[schema1, schema2], // first level
+ /// &[schema3, schema4], // second level
+ /// ]
+ /// ```
+ ///
+ /// Will search for a matching field in all schemas in the first level. If a matching field according to above
+ /// mentioned conditions is not found, then will check the next level. If found more than one matching column across
+ /// all schemas in a level, that isn't a USING column, will return an error due to ambiguous column.
+ ///
+ /// If checked all levels and couldn't find field, will return field not found error.
+ pub fn normalize_with_schemas_and_ambiguity_check(
+ self,
+ schemas: &[&[&DFSchema]],
+ using_columns: &[HashSet<Column>],
+ ) -> Result<Self> {
+ if self.relation.is_some() {
+ return Ok(self);
+ }
+
+ for schema_level in schemas {
+ let fields = schema_level
+ .iter()
+ .flat_map(|s| s.fields_with_unqualified_name(&self.name))
+ .collect::<Vec<_>>();
+ match fields.len() {
+ 0 => continue,
+ 1 => return Ok(fields[0].qualified_column()),
+ _ => {
+ // More than 1 fields in this schema have their names set to self.name.
+ //
+ // This should only happen when a JOIN query with USING constraint references
+ // join columns using unqualified column name. For example:
+ //
+ // ```sql
+ // SELECT id FROM t1 JOIN t2 USING(id)
+ // ```
+ //
+ // In this case, both `t1.id` and `t2.id` will match unqualified column `id`.
+ // We will use the relation from the first matched field to normalize self.
+
+ // Compare matched fields with one USING JOIN clause at a time
+ for using_col in using_columns {
+ let all_matched = fields
+ .iter()
+ .all(|f| using_col.contains(&f.qualified_column()));
+ // All matched fields belong to the same using column set, in orther words
+ // the same join clause. We simply pick the qualifer from the first match.
+ if all_matched {
+ return Ok(fields[0].qualified_column());
+ }
+ }
+
+ // If not due to USING columns then due to ambiguous column name
+ return Err(DataFusionError::SchemaError(
+ SchemaError::AmbiguousReference {
+ qualifier: None,
+ name: self.name,
+ },
+ ));
+ }
+ }
+ }
+
+ Err(DataFusionError::SchemaError(SchemaError::FieldNotFound {
+ field: self,
+ valid_fields: schemas
+ .iter()
+ .flat_map(|s| s.iter())
+ .flat_map(|s| s.fields().iter().map(|f| f.qualified_column()))
+ .collect(),
+ }))
+ }
}
impl From<&str> for Column {
@@ -189,3 +292,92 @@ impl fmt::Display for Column {
write!(f, "{}", self.flat_name())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::DFField;
+ use arrow::datatypes::DataType;
+ use std::collections::HashMap;
+
+ fn create_schema(names: &[(Option<&str>, &str)]) -> Result<DFSchema> {
+ let fields = names
+ .iter()
+ .map(|(qualifier, name)| {
+ DFField::new(qualifier.to_owned(), name, DataType::Boolean, true)
+ })
+ .collect::<Vec<_>>();
+ DFSchema::new_with_metadata(fields, HashMap::new())
+ }
+
+ #[test]
+ fn test_normalize_with_schemas_and_ambiguity_check() -> Result<()> {
+ let schema1 = create_schema(&[(Some("t1"), "a"), (Some("t1"), "b")])?;
+ let schema2 = create_schema(&[(Some("t2"), "c"), (Some("t2"), "d")])?;
+ let schema3 = create_schema(&[
+ (Some("t3"), "a"),
+ (Some("t3"), "b"),
+ (Some("t3"), "c"),
+ (Some("t3"), "d"),
+ (Some("t3"), "e"),
+ ])?;
+
+ // already normalized
+ let col = Column::new(Some("t1"), "a");
+ let col = col.normalize_with_schemas_and_ambiguity_check(&[], &[])?;
+ assert_eq!(col, Column::new(Some("t1"), "a"));
+
+ // should find in first level (schema1)
+ let col = Column::from_name("a");
+ let col = col.normalize_with_schemas_and_ambiguity_check(
+ &[&[&schema1, &schema2], &[&schema3]],
+ &[],
+ )?;
+ assert_eq!(col, Column::new(Some("t1"), "a"));
+
+ // should find in second level (schema3)
+ let col = Column::from_name("e");
+ let col = col.normalize_with_schemas_and_ambiguity_check(
+ &[&[&schema1, &schema2], &[&schema3]],
+ &[],
+ )?;
+ assert_eq!(col, Column::new(Some("t3"), "e"));
+
+ // using column in first level (pick schema1)
+ let mut using_columns = HashSet::new();
+ using_columns.insert(Column::new(Some("t1"), "a"));
+ using_columns.insert(Column::new(Some("t3"), "a"));
+ let col = Column::from_name("a");
+ let col = col.normalize_with_schemas_and_ambiguity_check(
+ &[&[&schema1, &schema3], &[&schema2]],
+ &[using_columns],
+ )?;
+ assert_eq!(col, Column::new(Some("t1"), "a"));
+
+ // not found in any level
+ let col = Column::from_name("z");
+ let err = col
+ .normalize_with_schemas_and_ambiguity_check(
+ &[&[&schema1, &schema2], &[&schema3]],
+ &[],
+ )
+ .expect_err("should've failed to find field");
+ let expected = "Schema error: No field named 'z'. \
+ Valid fields are 't1'.'a', 't1'.'b', 't2'.'c', \
+ 't2'.'d', 't3'.'a', 't3'.'b', 't3'.'c', 't3'.'d', 't3'.'e'.";
+ assert_eq!(err.to_string(), expected);
+
+ // ambiguous column reference
+ let col = Column::from_name("a");
+ let err = col
+ .normalize_with_schemas_and_ambiguity_check(
+ &[&[&schema1, &schema3], &[&schema2]],
+ &[],
+ )
+ .expect_err("should've found ambiguous field");
+ let expected = "Schema error: Ambiguous reference to unqualified field 'a'";
+ assert_eq!(err.to_string(), expected);
+
+ Ok(())
+ }
+}
diff --git a/datafusion/core/src/dataframe.rs b/datafusion/core/src/dataframe.rs
index aa8e1801bb..7cdbaa43ca 100644
--- a/datafusion/core/src/dataframe.rs
+++ b/datafusion/core/src/dataframe.rs
@@ -1393,8 +1393,7 @@ mod tests {
let join = left
.join_on(right, JoinType::Inner, [col("c1").eq(col("c1"))])
.expect_err("join didn't fail check");
- let expected =
- "Error during planning: reference 'c1' is ambiguous, could be a.c1,b.c1;";
+ let expected = "Schema error: Ambiguous reference to unqualified field 'c1'";
assert_eq!(join.to_string(), expected);
Ok(())
@@ -1861,7 +1860,7 @@ mod tests {
)]));
let data = RecordBatch::try_new(
- schema.clone(),
+ schema,
vec![
Arc::new(arrow::array::StringArray::from(vec![
Some("2a0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
diff --git a/datafusion/core/tests/dataframe.rs b/datafusion/core/tests/dataframe.rs
index 453b8f5cb7..b619262e07 100644
--- a/datafusion/core/tests/dataframe.rs
+++ b/datafusion/core/tests/dataframe.rs
@@ -33,7 +33,7 @@ use datafusion::prelude::JoinType;
use datafusion::prelude::{CsvReadOptions, ParquetReadOptions};
use datafusion::{assert_batches_eq, assert_batches_sorted_eq};
use datafusion_expr::expr::{GroupingSet, Sort};
-use datafusion_expr::{avg, col, count, lit, sum, Expr, ExprSchemable};
+use datafusion_expr::{avg, col, count, lit, max, sum, Expr, ExprSchemable};
#[tokio::test]
async fn describe() -> Result<()> {
@@ -201,6 +201,7 @@ async fn sort_on_distinct_columns() -> Result<()> {
assert_batches_eq!(expected, &results);
Ok(())
}
+
#[tokio::test]
async fn sort_on_distinct_unprojected_columns() -> Result<()> {
let schema = Schema::new(vec![
@@ -214,26 +215,98 @@ async fn sort_on_distinct_unprojected_columns() -> Result<()> {
Arc::new(Int32Array::from_slice([1, 10, 10, 100])),
Arc::new(Int32Array::from_slice([2, 3, 4, 5])),
],
- )
- .unwrap();
+ )?;
// Cannot sort on a column after distinct that would add a new column
let ctx = SessionContext::new();
- ctx.register_batch("t", batch).unwrap();
+ ctx.register_batch("t", batch)?;
let err = ctx
.table("t")
- .await
- .unwrap()
- .select(vec![col("a")])
- .unwrap()
- .distinct()
- .unwrap()
+ .await?
+ .select(vec![col("a")])?
+ .distinct()?
.sort(vec![Expr::Sort(Sort::new(Box::new(col("b")), false, true))])
.unwrap_err();
assert_eq!(err.to_string(), "Error during planning: For SELECT DISTINCT, ORDER BY expressions b must appear in select list");
Ok(())
}
+#[tokio::test]
+async fn sort_on_ambiguous_column() -> Result<()> {
+ let err = create_test_table("t1")
+ .await?
+ .join(
+ create_test_table("t2").await?,
+ JoinType::Inner,
+ &["a"],
+ &["a"],
+ None,
+ )?
+ .sort(vec![col("b").sort(true, true)])
+ .unwrap_err();
+
+ let expected = "Schema error: Ambiguous reference to unqualified field 'b'";
+ assert_eq!(err.to_string(), expected);
+ Ok(())
+}
+
+#[tokio::test]
+async fn group_by_ambiguous_column() -> Result<()> {
+ let err = create_test_table("t1")
+ .await?
+ .join(
+ create_test_table("t2").await?,
+ JoinType::Inner,
+ &["a"],
+ &["a"],
+ None,
+ )?
+ .aggregate(vec![col("b")], vec![max(col("a"))])
+ .unwrap_err();
+
+ let expected = "Schema error: Ambiguous reference to unqualified field 'b'";
+ assert_eq!(err.to_string(), expected);
+ Ok(())
+}
+
+#[tokio::test]
+async fn filter_on_ambiguous_column() -> Result<()> {
+ let err = create_test_table("t1")
+ .await?
+ .join(
+ create_test_table("t2").await?,
+ JoinType::Inner,
+ &["a"],
+ &["a"],
+ None,
+ )?
+ .filter(col("b").eq(lit(1)))
+ .unwrap_err();
+
+ let expected = "Schema error: Ambiguous reference to unqualified field 'b'";
+ assert_eq!(err.to_string(), expected);
+ Ok(())
+}
+
+#[tokio::test]
+async fn select_ambiguous_column() -> Result<()> {
+ let err = create_test_table("t1")
+ .await?
+ .join(
+ create_test_table("t2").await?,
+ JoinType::Inner,
+ &["a"],
+ &["a"],
+ None,
+ )?
+ .select(vec![col("b")])
+ .unwrap_err();
+
+ let expected = "Schema error: Ambiguous reference to unqualified field 'b'";
+ assert_eq!(err.to_string(), expected);
+ Ok(())
+}
+
#[tokio::test]
async fn filter_with_alias_overwrite() -> Result<()> {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
@@ -316,7 +389,7 @@ async fn test_grouping_sets() -> Result<()> {
vec![col("a"), col("b")],
]));
- let df = create_test_table()
+ let df = create_test_table("test")
.await?
.aggregate(vec![grouping_set_expr], vec![count(col("a"))])?
.sort(vec![
@@ -746,7 +819,7 @@ async fn unnest_aggregate_columns() -> Result<()> {
Ok(())
}
-async fn create_test_table() -> Result<DataFrame> {
+async fn create_test_table(name: &str) -> Result<DataFrame> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Utf8, false),
Field::new("b", DataType::Int32, false),
@@ -768,9 +841,9 @@ async fn create_test_table() -> Result<DataFrame> {
let ctx = SessionContext::new();
- ctx.register_batch("test", batch)?;
+ ctx.register_batch(name, batch)?;
- ctx.table("test").await
+ ctx.table(name).await
}
async fn aggregates_table(ctx: &SessionContext) -> Result<DataFrame> {
diff --git a/datafusion/expr/src/expr_rewriter.rs b/datafusion/expr/src/expr_rewriter.rs
index af672a85ce..3ae9e43e0f 100644
--- a/datafusion/expr/src/expr_rewriter.rs
+++ b/datafusion/expr/src/expr_rewriter.rs
@@ -22,7 +22,7 @@ use crate::expr::{
Like, Sort, TryCast, WindowFunction,
};
use crate::logical_plan::Projection;
-use crate::{Expr, ExprSchemable, LogicalPlan};
+use crate::{Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder};
use datafusion_common::Result;
use datafusion_common::{Column, DFSchema};
use std::collections::HashMap;
@@ -344,11 +344,23 @@ where
/// Recursively call [`Column::normalize_with_schemas`] on all [`Column`] expressions
/// in the `expr` expression tree.
pub fn normalize_col(expr: Expr, plan: &LogicalPlan) -> Result<Expr> {
- normalize_col_with_schemas(expr, &plan.all_schemas(), &plan.using_columns()?)
+ rewrite_expr(expr, |expr| {
+ if let Expr::Column(c) = expr {
+ let col = LogicalPlanBuilder::normalize(plan, c)?;
+ Ok(Expr::Column(col))
+ } else {
+ Ok(expr)
+ }
+ })
}
/// Recursively call [`Column::normalize_with_schemas`] on all [`Column`] expressions
/// in the `expr` expression tree.
+#[deprecated(
+ since = "20.0.0",
+ note = "use normalize_col_with_schemas_and_ambiguity_check instead"
+)]
+#[allow(deprecated)]
pub fn normalize_col_with_schemas(
expr: Expr,
schemas: &[&Arc<DFSchema>],
@@ -365,6 +377,24 @@ pub fn normalize_col_with_schemas(
})
}
+/// See [`Column::normalize_with_schemas_and_ambiguity_check`] for usage
+pub fn normalize_col_with_schemas_and_ambiguity_check(
+ expr: Expr,
+ schemas: &[&[&DFSchema]],
+ using_columns: &[HashSet<Column>],
+) -> Result<Expr> {
+ rewrite_expr(expr, |expr| {
+ if let Expr::Column(c) = expr {
+ Ok(Expr::Column(c.normalize_with_schemas_and_ambiguity_check(
+ schemas,
+ using_columns,
+ )?))
+ } else {
+ Ok(expr)
+ }
+ })
+}
+
/// Recursively normalize all [`Column`] expressions in a list of expression trees
pub fn normalize_cols(
exprs: impl IntoIterator<Item = impl Into<Expr>>,
@@ -600,13 +630,12 @@ mod test {
make_field("tableC", "f"),
make_field("tableC", "ff"),
]);
- let schemas = vec![schema_c, schema_f, schema_b, schema_a]
- .into_iter()
- .map(Arc::new)
- .collect::<Vec<_>>();
+ let schemas = vec![schema_c, schema_f, schema_b, schema_a];
let schemas = schemas.iter().collect::<Vec<_>>();
- let normalized_expr = normalize_col_with_schemas(expr, &schemas, &[]).unwrap();
+ let normalized_expr =
+ normalize_col_with_schemas_and_ambiguity_check(expr, &[&schemas], &[])
+ .unwrap();
assert_eq!(
normalized_expr,
col("tableA.a") + col("tableB.b") + col("tableC.c")
@@ -614,6 +643,7 @@ mod test {
}
#[test]
+ #[allow(deprecated)]
fn normalize_cols_priority() {
let expr = col("a") + col("b");
// Schemas with multiple matches for column a, first takes priority
@@ -635,12 +665,13 @@ mod test {
// test normalizing columns when the name doesn't exist
let expr = col("a") + col("b");
let schema_a = make_schema_with_empty_metadata(vec![make_field("tableA", "a")]);
- let schemas = vec![schema_a].into_iter().map(Arc::new).collect::<Vec<_>>();
+ let schemas = vec![schema_a];
let schemas = schemas.iter().collect::<Vec<_>>();
- let error = normalize_col_with_schemas(expr, &schemas, &[])
- .unwrap_err()
- .to_string();
+ let error =
+ normalize_col_with_schemas_and_ambiguity_check(expr, &[&schemas], &[])
+ .unwrap_err()
+ .to_string();
assert_eq!(
error,
"Schema error: No field named 'b'. Valid fields are 'tableA'.'a'."
diff --git a/datafusion/expr/src/logical_plan/builder.rs b/datafusion/expr/src/logical_plan/builder.rs
index 0461a1d858..a1fa82cda2 100644
--- a/datafusion/expr/src/logical_plan/builder.rs
+++ b/datafusion/expr/src/logical_plan/builder.rs
@@ -18,14 +18,12 @@
//! This module provides a builder for creating LogicalPlans
use crate::expr_rewriter::{
- coerce_plan_expr_for_schema, normalize_col, normalize_col_with_schemas,
- normalize_cols, rewrite_sort_cols_by_aggs,
+ coerce_plan_expr_for_schema, normalize_col,
+ normalize_col_with_schemas_and_ambiguity_check, normalize_cols,
+ rewrite_sort_cols_by_aggs,
};
use crate::type_coercion::binary::comparison_coercion;
-use crate::utils::{
- columnize_expr, compare_sort_expr, ensure_any_column_reference_is_unambiguous,
- exprlist_to_fields, from_plan,
-};
+use crate::utils::{columnize_expr, compare_sort_expr, exprlist_to_fields, from_plan};
use crate::{and, binary_expr, Operator};
use crate::{
logical_plan::{
@@ -552,15 +550,17 @@ impl LogicalPlanBuilder {
self.join_detailed(right, join_type, join_keys, filter, false)
}
- fn normalize(
+ pub(crate) fn normalize(
plan: &LogicalPlan,
column: impl Into<Column> + Clone,
) -> Result<Column> {
- let schemas = plan.all_schemas();
+ let schema = plan.schema();
+ let fallback_schemas = plan.fallback_normalize_schemas();
let using_columns = plan.using_columns()?;
- column
- .into()
- .normalize_with_schemas(&schemas, &using_columns)
+ column.into().normalize_with_schemas_and_ambiguity_check(
+ &[&[schema], &fallback_schemas],
+ &using_columns,
+ )
}
/// Apply a join with on constraint and specified null equality
@@ -580,18 +580,10 @@ impl LogicalPlanBuilder {
}
let filter = if let Some(expr) = filter {
- // ambiguous check
- ensure_any_column_reference_is_unambiguous(
- &expr,
- &[self.schema(), right.schema()],
- )?;
-
- // normalize all columns in expression
- let using_columns = expr.to_columns()?;
- let filter = normalize_col_with_schemas(
+ let filter = normalize_col_with_schemas_and_ambiguity_check(
expr,
- &[self.schema(), right.schema()],
- &[using_columns],
+ &[&[self.schema(), right.schema()]],
+ &[],
)?;
Some(filter)
} else {
@@ -947,16 +939,16 @@ impl LogicalPlanBuilder {
let right_key = r.into();
let left_using_columns = left_key.to_columns()?;
- let normalized_left_key = normalize_col_with_schemas(
+ let normalized_left_key = normalize_col_with_schemas_and_ambiguity_check(
left_key,
- &[self.plan.schema(), right.schema()],
+ &[&[self.plan.schema(), right.schema()]],
&[left_using_columns],
)?;
let right_using_columns = right_key.to_columns()?;
- let normalized_right_key = normalize_col_with_schemas(
+ let normalized_right_key = normalize_col_with_schemas_and_ambiguity_check(
right_key,
- &[self.plan.schema(), right.schema()],
+ &[&[self.plan.schema(), right.schema()]],
&[right_using_columns],
)?;
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index 2ce1b10972..83bda06122 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -174,7 +174,26 @@ impl LogicalPlan {
}
}
+ /// Used for normalizing columns, as the fallback schemas to the main schema
+ /// of the plan.
+ pub fn fallback_normalize_schemas(&self) -> Vec<&DFSchema> {
+ match self {
+ LogicalPlan::Window(_)
+ | LogicalPlan::Projection(_)
+ | LogicalPlan::Aggregate(_)
+ | LogicalPlan::Unnest(_)
+ | LogicalPlan::Join(_)
+ | LogicalPlan::CrossJoin(_) => self
+ .inputs()
+ .iter()
+ .map(|input| input.schema().as_ref())
+ .collect(),
+ _ => vec![],
+ }
+ }
+
/// Get all meaningful schemas of a plan and its children plan.
+ #[deprecated(since = "20.0.0")]
pub fn all_schemas(&self) -> Vec<&DFSchemaRef> {
match self {
// return self and children schemas
@@ -2439,6 +2458,7 @@ mod tests {
}
#[test]
+ #[allow(deprecated)]
fn test_extension_all_schemas() {
let plan = LogicalPlan::Extension(Extension {
node: Arc::new(NoChildExtension::empty()),
diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rs
index 8c1be46871..95b5f881b3 100644
--- a/datafusion/expr/src/utils.rs
+++ b/datafusion/expr/src/utils.rs
@@ -37,7 +37,7 @@ use datafusion_common::{
Column, DFField, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,
};
use std::cmp::Ordering;
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
use std::sync::Arc;
/// The value to which `COUNT(*)` is expanded to in
@@ -96,41 +96,7 @@ pub fn expr_to_columns(expr: &Expr, accum: &mut HashSet<Column>) -> Result<()> {
Expr::ScalarVariable(_, var_names) => {
accum.insert(Column::from_name(var_names.join(".")));
}
- Expr::Alias(_, _)
- | Expr::Literal(_)
- | Expr::BinaryExpr { .. }
- | Expr::Like { .. }
- | Expr::ILike { .. }
- | Expr::SimilarTo { .. }
- | Expr::Not(_)
- | Expr::IsNotNull(_)
- | Expr::IsNull(_)
- | Expr::IsTrue(_)
- | Expr::IsFalse(_)
- | Expr::IsUnknown(_)
- | Expr::IsNotTrue(_)
- | Expr::IsNotFalse(_)
- | Expr::IsNotUnknown(_)
- | Expr::Negative(_)
- | Expr::Between { .. }
- | Expr::Case { .. }
- | Expr::Cast { .. }
- | Expr::TryCast { .. }
- | Expr::Sort { .. }
- | Expr::ScalarFunction { .. }
- | Expr::ScalarUDF { .. }
- | Expr::WindowFunction { .. }
- | Expr::AggregateFunction { .. }
- | Expr::GroupingSet(_)
- | Expr::AggregateUDF { .. }
- | Expr::InList { .. }
- | Expr::Exists { .. }
- | Expr::InSubquery { .. }
- | Expr::ScalarSubquery(_)
- | Expr::Wildcard
- | Expr::QualifiedWildcard { .. }
- | Expr::GetIndexedField { .. }
- | Expr::Placeholder { .. } => {}
+ _ => {}
}
Ok(())
})
@@ -1035,65 +1001,6 @@ pub fn find_valid_equijoin_key_pair(
Ok(join_key_pair)
}
-/// Ensure any column reference of the expression is unambiguous.
-/// Assume we have two schema:
-/// schema1: a, b ,c
-/// schema2: a, d, e
-///
-/// `schema1.a + schema2.a` is unambiguous.
-/// `a + d` is ambiguous, because `a` may come from schema1 or schema2.
-pub fn ensure_any_column_reference_is_unambiguous(
- expr: &Expr,
- schemas: &[&DFSchema],
-) -> Result<()> {
- if schemas.len() == 1 {
- return Ok(());
- }
- // all referenced columns in the expression that don't have relation
- let referenced_cols = expr.to_columns()?;
- let mut no_relation_cols = referenced_cols
- .iter()
- .filter_map(|col| {
- if col.relation.is_none() {
- Some((col.name.as_str(), 0))
- } else {
- None
- }
- })
- .collect::<HashMap<&str, u8>>();
- // find the name of the column existing in multi schemas.
- let ambiguous_col_name = schemas
- .iter()
- .flat_map(|schema| schema.fields())
- .map(|field| field.name())
- .find(|col_name| {
- no_relation_cols.entry(col_name).and_modify(|v| *v += 1);
- matches!(
- no_relation_cols.get_key_value(col_name.as_str()),
- Some((_, 2..))
- )
- });
-
- if let Some(col_name) = ambiguous_col_name {
- let maybe_field = schemas
- .iter()
- .flat_map(|schema| {
- schema
- .field_with_unqualified_name(col_name)
- .map(|f| f.qualified_name())
- .ok()
- })
- .collect::<Vec<_>>();
- Err(DataFusionError::Plan(format!(
- "reference \'{}\' is ambiguous, could be {};",
- col_name,
- maybe_field.join(","),
- )))
- } else {
- Ok(())
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs
index 3858a7ff58..f910268dfe 100644
--- a/datafusion/optimizer/src/push_down_filter.rs
+++ b/datafusion/optimizer/src/push_down_filter.rs
@@ -1491,7 +1491,7 @@ mod tests {
(vec![Column::from_name("a")], vec![Column::from_name("a")]),
None,
)?
- .filter(col("a").lt_eq(lit(1i64)))?
+ .filter(col("test.a").lt_eq(lit(1i64)))?
.build()?;
// not part of the test, just good to know:
diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rs
index 0feb7fbacb..bdf9a7c302 100644
--- a/datafusion/sql/src/select.rs
+++ b/datafusion/sql/src/select.rs
@@ -20,14 +20,14 @@ use crate::utils::{
check_columns_satisfy_exprs, extract_aliases, normalize_ident, rebase_expr,
resolve_aliases_to_exprs, resolve_columns, resolve_positions_to_exprs,
};
-use datafusion_common::{Column, DFSchema, DFSchemaRef, DataFusionError, Result};
-use datafusion_expr::expr_rewriter::{normalize_col, normalize_col_with_schemas};
+use datafusion_common::{DFSchema, DataFusionError, Result};
+use datafusion_expr::expr_rewriter::{
+ normalize_col, normalize_col_with_schemas_and_ambiguity_check,
+};
use datafusion_expr::logical_plan::builder::project;
-use datafusion_expr::logical_plan::Join as HashJoin;
-use datafusion_expr::logical_plan::JoinConstraint as HashJoinConstraint;
use datafusion_expr::utils::{
expand_qualified_wildcard, expand_wildcard, expr_as_column_expr, expr_to_columns,
- find_aggregate_exprs, find_column_exprs, find_window_exprs,
+ find_aggregate_exprs, find_window_exprs,
};
use datafusion_expr::Expr::Alias;
use datafusion_expr::{
@@ -66,9 +66,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
// process `from` clause
let plan = self.plan_from_tables(select.from, planner_context)?;
let empty_from = matches!(plan, LogicalPlan::EmptyRelation(_));
- // build from schema for unqualifier column ambiguous check
- // we should get only one field for unqualifier column from schema.
- let from_schema = self.build_schema_for_ambiguous_check(&plan)?;
// process `where` clause
let plan = self.plan_selection(
@@ -76,7 +73,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
plan,
outer_query_schema,
planner_context,
- &from_schema,
)?;
// process the SELECT expressions, with wildcards expanded.
@@ -85,7 +81,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
select.projection,
empty_from,
planner_context,
- &from_schema,
)?;
// having and group by clause may reference aliases defined in select projection
@@ -241,33 +236,26 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
plan: LogicalPlan,
outer_query_schema: Option<&DFSchema>,
planner_context: &mut PlannerContext,
- from_schema: &DFSchema,
) -> Result<LogicalPlan> {
match selection {
Some(predicate_expr) => {
let mut join_schema = (**plan.schema()).clone();
- let mut all_schemas: Vec<DFSchemaRef> = vec![];
- for schema in plan.all_schemas() {
- all_schemas.push(schema.clone());
- }
- if let Some(outer) = outer_query_schema {
- all_schemas.push(Arc::new(outer.clone()));
+
+ let fallback_schemas = plan.fallback_normalize_schemas();
+ let outer_query_schema = if let Some(outer) = outer_query_schema {
join_schema.merge(outer);
- }
- let x: Vec<&DFSchemaRef> = all_schemas.iter().collect();
+ vec![outer]
+ } else {
+ vec![]
+ };
let filter_expr =
self.sql_to_expr(predicate_expr, &join_schema, planner_context)?;
- self.column_reference_ambiguous_check(
- &[filter_expr.clone()],
- from_schema,
- outer_query_schema,
- )?;
let mut using_columns = HashSet::new();
expr_to_columns(&filter_expr, &mut using_columns)?;
- let filter_expr = normalize_col_with_schemas(
+ let filter_expr = normalize_col_with_schemas_and_ambiguity_check(
filter_expr,
- x.as_slice(),
+ &[&[plan.schema()], &fallback_schemas, &outer_query_schema],
&[using_columns],
)?;
@@ -315,19 +303,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
projection: Vec<SelectItem>,
empty_from: bool,
planner_context: &mut PlannerContext,
- from_schema: &DFSchema,
) -> Result<Vec<Expr>> {
projection
.into_iter()
- .map(|expr| {
- self.sql_select_to_rex(
- expr,
- plan,
- empty_from,
- planner_context,
- from_schema,
- )
- })
+ .map(|expr| self.sql_select_to_rex(expr, plan, empty_from, planner_context))
.flat_map(|result| match result {
Ok(vec) => vec.into_iter().map(Ok).collect(),
Err(err) => vec![Err(err)],
@@ -342,28 +321,27 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
plan: &LogicalPlan,
empty_from: bool,
planner_context: &mut PlannerContext,
- from_schema: &DFSchema,
) -> Result<Vec<Expr>> {
match sql {
SelectItem::UnnamedExpr(expr) => {
let expr = self.sql_to_expr(expr, plan.schema(), planner_context)?;
- self.column_reference_ambiguous_check(
- &[expr.clone()],
- from_schema,
- None,
+ let col = normalize_col_with_schemas_and_ambiguity_check(
+ expr,
+ &[&[plan.schema()]],
+ &plan.using_columns()?,
)?;
- Ok(vec![normalize_col(expr, plan)?])
+ Ok(vec![col])
}
SelectItem::ExprWithAlias { expr, alias } => {
let select_expr =
self.sql_to_expr(expr, plan.schema(), planner_context)?;
- self.column_reference_ambiguous_check(
- &[select_expr.clone()],
- from_schema,
- None,
+ let col = normalize_col_with_schemas_and_ambiguity_check(
+ select_expr,
+ &[&[plan.schema()]],
+ &plan.using_columns()?,
)?;
- let expr = Alias(Box::new(select_expr), normalize_ident(alias));
- Ok(vec![normalize_col(expr, plan)?])
+ let expr = Alias(Box::new(col), normalize_ident(alias));
+ Ok(vec![expr])
}
SelectItem::Wildcard(options) => {
Self::check_wildcard_options(options)?;
@@ -386,49 +364,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}
}
- /// ambiguous check for unqualifier column
- fn column_reference_ambiguous_check(
- &self,
- exprs: &[Expr],
- schema: &DFSchema,
- fallback_schema: Option<&DFSchema>,
- ) -> Result<()> {
- find_column_exprs(exprs)
- .iter()
- .try_for_each(|col| match col {
- Expr::Column(Column {
- name,
- relation: None,
- ..
- }) => {
- match (
- schema.fields_with_unqualified_name(name).len(),
- fallback_schema,
- ) {
- // in case is from outer query if this is inner subquery
- (0, Some(fallback_schema)) => {
- match fallback_schema.fields_with_unqualified_name(name).len()
- {
- 0 => Err(DataFusionError::Plan(format!(
- "column reference {name} is unknown",
- ))),
- 1 => Ok(()),
- _ => Err(DataFusionError::Plan(format!(
- "column reference {name} is ambiguous",
- ))),
- }
- }
- (1, _) => Ok(()),
- // should get only one field in from_schema.
- _ => Err(DataFusionError::Plan(format!(
- "column reference {name} is ambiguous",
- ))),
- }
- }
- _ => Ok(()),
- })
- }
-
fn check_wildcard_options(options: WildcardAdditionalOptions) -> Result<()> {
let WildcardAdditionalOptions {
opt_exclude,
@@ -451,34 +386,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}
}
- /// build schema for unqualifier column ambiguous check
- fn build_schema_for_ambiguous_check(&self, plan: &LogicalPlan) -> Result<DFSchema> {
- let mut fields = plan.schema().fields().clone();
-
- let metadata = plan.schema().metadata().clone();
- if let LogicalPlan::Join(HashJoin {
- join_constraint: HashJoinConstraint::Using,
- ref on,
- ref left,
- ..
- }) = plan
- {
- // For query: select id from t1 join t2 using(id), this is legal.
- // We should dedup the fields for cols in using clause.
- for join_keys in on.iter() {
- let join_col = &join_keys.0.try_into_col()?;
- let left_field = left.schema().field_from_column(join_col)?;
- fields.retain(|field| {
- field.unqualified_column().name
- != left_field.unqualified_column().name
- });
- fields.push(left_field.clone());
- }
- }
-
- DFSchema::new_with_metadata(fields, metadata)
- }
-
/// Wrap a plan in a projection
fn project(&self, input: LogicalPlan, expr: Vec<Expr>) -> Result<LogicalPlan> {
self.validate_schema_satisfies_exprs(input.schema(), &expr)?;
diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rs
index 67eb7f315d..fa0eed1b90 100644
--- a/datafusion/sql/src/statement.rs
+++ b/datafusion/sql/src/statement.rs
@@ -28,7 +28,7 @@ use datafusion_common::{
Column, DFField, DFSchema, DFSchemaRef, DataFusionError, ExprSchema,
OwnedTableReference, Result, TableReference, ToDFSchema,
};
-use datafusion_expr::expr_rewriter::normalize_col_with_schemas;
+use datafusion_expr::expr_rewriter::normalize_col_with_schemas_and_ambiguity_check;
use datafusion_expr::logical_plan::builder::project;
use datafusion_expr::logical_plan::{Analyze, Prepare};
use datafusion_expr::utils::expr_to_columns;
@@ -652,9 +652,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
let schema = Arc::new(schema.clone());
let mut using_columns = HashSet::new();
expr_to_columns(&filter_expr, &mut using_columns)?;
- let filter_expr = normalize_col_with_schemas(
+ let filter_expr = normalize_col_with_schemas_and_ambiguity_check(
filter_expr,
- &[&schema],
+ &[&[&schema]],
&[using_columns],
)?;
LogicalPlan::Filter(Filter::try_new(filter_expr, Arc::new(scan))?)
@@ -737,9 +737,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
)?;
let mut using_columns = HashSet::new();
expr_to_columns(&filter_expr, &mut using_columns)?;
- let filter_expr = normalize_col_with_schemas(
+ let filter_expr = normalize_col_with_schemas_and_ambiguity_check(
filter_expr,
- &[&table_schema],
+ &[&[&table_schema]],
&[using_columns],
)?;
LogicalPlan::Filter(Filter::try_new(filter_expr, Arc::new(scan))?)
diff --git a/datafusion/sql/tests/integration_test.rs b/datafusion/sql/tests/integration_test.rs
index 6609599070..124ab0c698 100644
--- a/datafusion/sql/tests/integration_test.rs
+++ b/datafusion/sql/tests/integration_test.rs
@@ -515,7 +515,7 @@ fn select_with_ambiguous_column() {
let sql = "SELECT id FROM person a, person b";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
- "Plan(\"column reference id is ambiguous\")",
+ "SchemaError(AmbiguousReference { qualifier: None, name: \"id\" })",
format!("{err:?}")
);
}
@@ -538,7 +538,7 @@ fn where_selection_with_ambiguous_column() {
let sql = "SELECT * FROM person a, person b WHERE id = id + 1";
let err = logical_plan(sql).expect_err("query should have failed");
assert_eq!(
- "Plan(\"column reference id is ambiguous\")",
+ "SchemaError(AmbiguousReference { qualifier: None, name: \"id\" })",
format!("{err:?}")
);
}
@@ -2961,6 +2961,24 @@ fn order_by_unaliased_name() {
quick_test(sql, expected);
}
+#[test]
+fn order_by_ambiguous_name() {
+ let sql = "select * from person a join person b using (id) order by age";
+ let expected = "Schema error: Ambiguous reference to unqualified field 'age'";
+
+ let err = logical_plan(sql).unwrap_err();
+ assert_eq!(err.to_string(), expected);
+}
+
+#[test]
+fn group_by_ambiguous_name() {
+ let sql = "select max(id) from person a join person b using (id) group by age";
+ let expected = "Schema error: Ambiguous reference to unqualified field 'age'";
+
+ let err = logical_plan(sql).unwrap_err();
+ assert_eq!(err.to_string(), expected);
+}
+
#[test]
fn test_zero_offset_with_limit() {
let sql = "select id from person where person.id > 100 LIMIT 5 OFFSET 0;";
@@ -3260,8 +3278,7 @@ fn test_ambiguous_column_references_in_on_join() {
INNER JOIN person as p2
ON id = 1";
- let expected =
- "Error during planning: reference 'id' is ambiguous, could be p1.id,p2.id;";
+ let expected = "Schema error: Ambiguous reference to unqualified field 'id'";
// It should return error.
let result = logical_plan(sql);
diff --git a/datafusion/substrait/src/logical_plan/consumer.rs b/datafusion/substrait/src/logical_plan/consumer.rs
index 627e71638c..27f8093f76 100644
--- a/datafusion/substrait/src/logical_plan/consumer.rs
+++ b/datafusion/substrait/src/logical_plan/consumer.rs
@@ -505,10 +505,14 @@ pub async fn from_substrait_rex(
"Direct reference StructField with child is not supported"
.to_string(),
)),
- None => Ok(Arc::new(Expr::Column(Column {
- relation: None,
- name: input_schema.field(x.field as usize).name().to_string(),
- }))),
+ None => {
+ let column =
+ input_schema.field(x.field as usize).qualified_column();
+ Ok(Arc::new(Expr::Column(Column {
+ relation: column.relation,
+ name: column.name,
+ })))
+ }
},
_ => Err(DataFusionError::NotImplemented(
"Direct reference with types other than StructField is not supported"