Skip to content

Apache DataFusion SQL Query Engine

minor: SchemaError code cleanup and improvements (#2391)

Andy Groved639a0d27855
diff --git a/datafusion/common/src/column.rs b/datafusion/common/src/column.rs
index 02faa24b03..37fe172e33 100644
--- a/datafusion/common/src/column.rs
+++ b/datafusion/common/src/column.rs
@@ -17,7 +17,7 @@
//! Column
-use crate::{DFSchema, DataFusionError, Result};
+use crate::{DFSchema, DataFusionError, Result, SchemaError};
use std::collections::HashSet;
use std::convert::Infallible;
use std::fmt;
@@ -119,10 +119,16 @@ impl Column {
}
}
- Err(DataFusionError::Plan(format!(
- "Column {} not found in provided schemas",
- self
- )))
+ Err(DataFusionError::SchemaError(SchemaError::FieldNotFound {
+ qualifier: self.relation.clone(),
+ name: self.name,
+ valid_fields: Some(
+ schemas
+ .iter()
+ .flat_map(|s| s.fields().iter().map(|f| f.qualified_name()))
+ .collect(),
+ ),
+ }))
}
}
diff --git a/datafusion/common/src/dfschema.rs b/datafusion/common/src/dfschema.rs
index ec186899ff..6a0c639d03 100644
--- a/datafusion/common/src/dfschema.rs
+++ b/datafusion/common/src/dfschema.rs
@@ -23,7 +23,7 @@ use std::convert::TryFrom;
use std::sync::Arc;
use crate::error::{DataFusionError, Result, SchemaError};
-use crate::Column;
+use crate::{field_not_found, Column};
use arrow::compute::can_cast_types;
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
@@ -185,11 +185,7 @@ impl DFSchema {
}
}
- Err(DataFusionError::SchemaError(SchemaError::FieldNotExist {
- qualifier: None,
- name: name.to_string(),
- valid_fields: Some(self.get_field_names()),
- }))
+ Err(field_not_found(None, name, self))
}
pub fn index_of_column_by_name(
@@ -213,11 +209,11 @@ impl DFSchema {
})
.map(|(idx, _)| idx);
match matches.next() {
- None => Err(DataFusionError::SchemaError(SchemaError::FieldNotExist {
- qualifier: qualifier.map(|s| s.to_string()),
- name: name.to_string(),
- valid_fields: Some(self.get_field_names()),
- })),
+ None => Err(field_not_found(
+ qualifier.map(|s| s.to_string()),
+ name,
+ self,
+ )),
Some(idx) => match matches.next() {
None => Ok(idx),
// found more than one matches
@@ -268,11 +264,7 @@ impl DFSchema {
pub fn field_with_unqualified_name(&self, name: &str) -> Result<&DFField> {
let matches = self.fields_with_unqualified_name(name);
match matches.len() {
- 0 => Err(DataFusionError::SchemaError(SchemaError::FieldNotExist {
- qualifier: None,
- name: name.to_string(),
- valid_fields: Some(self.get_field_names()),
- })),
+ 0 => Err(field_not_found(None, name, self)),
1 => Ok(matches[0]),
_ => Err(DataFusionError::SchemaError(
SchemaError::AmbiguousReference {
@@ -357,14 +349,11 @@ impl DFSchema {
}
}
- /// Get comma-separated list of field names for use in error messages
- fn get_field_names(&self) -> Vec<String> {
+ /// Get list of fully-qualified field names in this schema
+ pub fn field_names(&self) -> Vec<String> {
self.fields
.iter()
- .map(|f| match f.qualifier() {
- Some(qualifier) => format!("'{}.{}'", qualifier, f.name()),
- None => format!("'{}'", f.name()),
- })
+ .map(|f| f.qualified_name())
.collect::<Vec<_>>()
}
diff --git a/datafusion/common/src/error.rs b/datafusion/common/src/error.rs
index 5e784f4ac5..807a916abc 100644
--- a/datafusion/common/src/error.rs
+++ b/datafusion/common/src/error.rs
@@ -22,6 +22,7 @@ use std::fmt::{Display, Formatter};
use std::io;
use std::result;
+use crate::DFSchema;
use arrow::error::ArrowError;
#[cfg(feature = "avro")]
use avro_rs::Error as AvroError;
@@ -94,17 +95,30 @@ pub enum SchemaError {
/// Schema contains duplicate unqualified field name
DuplicateUnqualifiedField { name: String },
/// No field with this name
- FieldNotExist {
+ FieldNotFound {
qualifier: Option<String>,
name: String,
valid_fields: Option<Vec<String>>,
},
}
+/// Create a "field not found" DataFusion::SchemaError
+pub fn field_not_found(
+ qualifier: Option<String>,
+ name: &str,
+ schema: &DFSchema,
+) -> DataFusionError {
+ DataFusionError::SchemaError(SchemaError::FieldNotFound {
+ qualifier,
+ name: name.to_string(),
+ valid_fields: Some(schema.field_names()),
+ })
+}
+
impl Display for SchemaError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
- Self::FieldNotExist {
+ Self::FieldNotFound {
qualifier,
name,
valid_fields,
@@ -116,7 +130,15 @@ impl Display for SchemaError {
write!(f, "'{}'", name)?;
}
if let Some(field_names) = valid_fields {
- write!(f, ". Valid fields are {}", field_names.join(", "))?;
+ write!(
+ f,
+ ". Valid fields are {}",
+ field_names
+ .iter()
+ .map(|name| format!("'{}'", name))
+ .collect::<Vec<String>>()
+ .join(", ")
+ )?;
}
write!(f, ".")
}
diff --git a/datafusion/common/src/lib.rs b/datafusion/common/src/lib.rs
index 824b0ca6c9..bcaed880a3 100644
--- a/datafusion/common/src/lib.rs
+++ b/datafusion/common/src/lib.rs
@@ -24,5 +24,5 @@ mod scalar;
pub use column::Column;
pub use dfschema::{DFField, DFSchema, DFSchemaRef, ExprSchema, ToDFSchema};
-pub use error::{DataFusionError, Result, SchemaError};
+pub use error::{field_not_found, DataFusionError, Result, SchemaError};
pub use scalar::{ScalarType, ScalarValue};
diff --git a/datafusion/core/src/logical_plan/expr_rewriter.rs b/datafusion/core/src/logical_plan/expr_rewriter.rs
index ef6d8dff9c..2c09d378ee 100644
--- a/datafusion/core/src/logical_plan/expr_rewriter.rs
+++ b/datafusion/core/src/logical_plan/expr_rewriter.rs
@@ -574,7 +574,7 @@ mod test {
.to_string();
assert_eq!(
error,
- "Error during planning: Column #b not found in provided schemas"
+ "Schema error: No field named 'b'. Valid fields are 'tableA.a'."
);
}
diff --git a/datafusion/core/src/sql/planner.rs b/datafusion/core/src/sql/planner.rs
index a04839f029..ca8cb23bc5 100644
--- a/datafusion/core/src/sql/planner.rs
+++ b/datafusion/core/src/sql/planner.rs
@@ -49,6 +49,7 @@ use arrow::datatypes::*;
use datafusion_expr::{window_function::WindowFunction, BuiltinScalarFunction};
use hashbrown::HashMap;
+use datafusion_common::field_not_found;
use datafusion_expr::logical_plan::Subquery;
use sqlparser::ast::{
BinaryOperator, DataType as SQLDataType, DateTimeField, Expr as SQLExpr, FunctionArg,
@@ -1253,18 +1254,16 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
if !schema.fields_with_unqualified_name(&col.name).is_empty() {
Ok(())
} else {
- Err(DataFusionError::Plan(format!(
- "No field with unqualified name '{}'",
- &col.name
- )))
+ Err(field_not_found(None, col.name.as_str(), schema))
}
}
}
.map_err(|_: DataFusionError| {
- DataFusionError::Plan(format!(
- "Invalid identifier '{}' for schema {}",
- col, schema
- ))
+ field_not_found(
+ col.relation.as_ref().map(|s| s.to_owned()),
+ col.name.as_str(),
+ schema,
+ )
}),
_ => Err(DataFusionError::Internal("Not a column".to_string())),
})
@@ -2544,10 +2543,7 @@ mod tests {
fn select_column_does_not_exist() {
let sql = "SELECT doesnotexist FROM person";
let err = logical_plan(sql).expect_err("query should have failed");
- assert!(matches!(
- err,
- DataFusionError::Plan(msg) if msg.contains("Invalid identifier '#doesnotexist' for schema "),
- ));
+ assert_field_not_found(err, "doesnotexist");
}
#[test]
@@ -2602,20 +2598,14 @@ mod tests {
fn select_filter_column_does_not_exist() {
let sql = "SELECT first_name FROM person WHERE doesnotexist = 'A'";
let err = logical_plan(sql).expect_err("query should have failed");
- assert!(matches!(
- err,
- DataFusionError::Plan(msg) if msg.contains("Invalid identifier '#doesnotexist' for schema "),
- ));
+ assert_field_not_found(err, "doesnotexist");
}
#[test]
fn select_filter_cannot_use_alias() {
let sql = "SELECT first_name AS x FROM person WHERE x = 'A'";
let err = logical_plan(sql).expect_err("query should have failed");
- assert!(matches!(
- err,
- DataFusionError::Plan(msg) if msg.contains("Invalid identifier '#x' for schema "),
- ));
+ assert_field_not_found(err, "x");
}
#[test]
@@ -3109,10 +3099,7 @@ mod tests {
fn select_simple_aggregate_column_does_not_exist() {
let sql = "SELECT MIN(doesnotexist) FROM person";
let err = logical_plan(sql).expect_err("query should have failed");
- assert!(matches!(
- err,
- DataFusionError::Plan(msg) if msg.contains("Invalid identifier '#doesnotexist' for schema "),
- ));
+ assert_field_not_found(err, "doesnotexist");
}
#[test]
@@ -3199,20 +3186,16 @@ mod tests {
fn select_simple_aggregate_with_groupby_and_column_in_group_by_does_not_exist() {
let sql = "SELECT SUM(age) FROM person GROUP BY doesnotexist";
let err = logical_plan(sql).expect_err("query should have failed");
- assert!(matches!(
- err,
- DataFusionError::Plan(msg) if msg.contains("Column #doesnotexist not found in provided schemas"),
- ));
+ assert_eq!("Schema error: No field named 'doesnotexist'. Valid fields are 'SUM(person.age)', \
+ 'person.id', 'person.first_name', 'person.last_name', 'person.age', 'person.state', \
+ 'person.salary', 'person.birth_date', 'person.😀'.", format!("{}", err));
}
#[test]
fn select_simple_aggregate_with_groupby_and_column_in_aggregate_does_not_exist() {
let sql = "SELECT SUM(doesnotexist) FROM person GROUP BY first_name";
let err = logical_plan(sql).expect_err("query should have failed");
- assert!(matches!(
- err,
- DataFusionError::Plan(msg) if msg.contains("Invalid identifier '#doesnotexist' for schema "),
- ));
+ assert_field_not_found(err, "doesnotexist");
}
#[test]
@@ -4557,4 +4540,17 @@ mod tests {
quick_test(sql, &expected)
}
+
+ fn assert_field_not_found(err: DataFusionError, name: &str) {
+ match err {
+ DataFusionError::SchemaError { .. } => {
+ let msg = format!("{}", err);
+ let expected = format!("Schema error: No field named '{}'.", name);
+ if !msg.starts_with(&expected) {
+ panic!("error [{}] did not start with [{}]", msg, expected);
+ }
+ }
+ _ => panic!("assert_field_not_found wrong error type"),
+ }
+ }
}
diff --git a/datafusion/core/tests/sql/idenfifers.rs b/datafusion/core/tests/sql/idenfifers.rs
index 71083e2743..f7b3baa836 100644
--- a/datafusion/core/tests/sql/idenfifers.rs
+++ b/datafusion/core/tests/sql/idenfifers.rs
@@ -215,28 +215,28 @@ async fn case_insensitive_in_sql_errors() {
.await
.unwrap_err()
.to_string();
- assert_contains!(actual, "Invalid identifier '#column1'");
+ assert_contains!(actual, "No field named 'column1'");
let actual = ctx
.sql("SELECT Column1 from test")
.await
.unwrap_err()
.to_string();
- assert_contains!(actual, "Invalid identifier '#column1'");
+ assert_contains!(actual, "No field named 'column1'");
let actual = ctx
.sql("SELECT column1 from test")
.await
.unwrap_err()
.to_string();
- assert_contains!(actual, "Invalid identifier '#column1'");
+ assert_contains!(actual, "No field named 'column1'");
let actual = ctx
.sql(r#"SELECT "column1" from test"#)
.await
.unwrap_err()
.to_string();
- assert_contains!(actual, "Invalid identifier '#column1'");
+ assert_contains!(actual, "No field named 'column1'");
// This should pass (note the quotes)
ctx.sql(r#"SELECT "Column1" from test"#).await.unwrap();