use datafusion::arrow::error::ArrowError;
use datafusion::error::DataFusionError;
use datafusion::sql::sqlparser::parser::ParserError;
pub mod matched {
pub const OPTIMIZER_RULE_FAILED: &str = "Optimizer rule";
pub const TOKENIZER_UNTERMINATED: &str = "Unterminated";
pub const TOKENIZER_EOF: &str = "EOF";
}
pub fn user_message(err: &DataFusionError) -> String {
match err {
DataFusionError::ArrowError(e, _) => arrow_message(e),
DataFusionError::ParquetError(e) => format!("Parquet: {e}"),
DataFusionError::ObjectStore(e) => e.to_string(),
DataFusionError::IoError(e) => e.to_string(),
DataFusionError::SQL(e, _) => parser_message(e),
DataFusionError::NotImplemented(m)
| DataFusionError::Plan(m)
| DataFusionError::Configuration(m)
| DataFusionError::Execution(m)
| DataFusionError::ResourcesExhausted(m)
| DataFusionError::Substrait(m)
| DataFusionError::Ffi(m) => m.clone(),
DataFusionError::Internal(m) => format!("internal error: {m}"),
DataFusionError::SchemaError(e, _) => e.to_string(),
DataFusionError::ExecutionJoin(e) => e.to_string(),
DataFusionError::External(e) => external_message(e.as_ref()),
DataFusionError::Context(context, inner)
if context.starts_with(matched::OPTIMIZER_RULE_FAILED) =>
{
user_message(inner)
}
DataFusionError::Context(context, inner) => {
format!("{context}: {}", user_message(inner))
}
DataFusionError::Diagnostic(_, inner) => user_message(inner),
DataFusionError::Collection(errs) => errs
.first()
.map(user_message)
.unwrap_or_else(|| "unknown error".to_string()),
DataFusionError::Shared(inner) => user_message(inner),
}
}
fn parser_message(e: &ParserError) -> String {
match e {
ParserError::TokenizerError(m) | ParserError::ParserError(m) => {
format!("syntax error: {m}")
}
ParserError::RecursionLimitExceeded => {
"syntax error: the statement is nested too deeply".to_string()
}
}
}
fn arrow_message(e: &ArrowError) -> String {
match e {
ArrowError::ExternalError(source) => external_message(source.as_ref()),
other => other.to_string(),
}
}
fn external_message(e: &(dyn std::error::Error + Send + Sync + 'static)) -> String {
if let Some(df) = e.downcast_ref::<DataFusionError>() {
user_message(df)
} else if let Some(arrow) = e.downcast_ref::<ArrowError>() {
arrow_message(arrow)
} else {
e.to_string()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use datafusion::common::tree_node::Transformed;
use datafusion::common::DFSchema;
use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
use datafusion::optimizer::{Optimizer, OptimizerConfig, OptimizerContext, OptimizerRule};
use datafusion::prelude::SessionContext;
use datafusion::sql::sqlparser::dialect::GenericDialect;
use datafusion::sql::sqlparser::tokenizer::Tokenizer;
use super::*;
#[derive(Debug)]
struct Failing;
impl OptimizerRule for Failing {
fn name(&self) -> &str {
"failing"
}
fn supports_rewrite(&self) -> bool {
true
}
fn rewrite(
&self,
_plan: LogicalPlan,
_config: &dyn OptimizerConfig,
) -> datafusion::error::Result<Transformed<LogicalPlan>> {
Err(DataFusionError::Plan("the cause".into()))
}
}
#[test]
fn datafusion_still_labels_a_failed_optimizer_rule() {
let optimizer = Optimizer::with_rules(vec![Arc::new(Failing)]);
let config = OptimizerContext::new().with_skip_failing_rules(false);
let plan = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::new(DFSchema::empty()),
});
let err = optimizer
.optimize(plan, &config, |_, _| {})
.expect_err("the rule fails");
let DataFusionError::Context(label, _) = &err else {
panic!(
"DataFusion no longer wraps a failed optimizer rule's error in a context: {err:?}"
);
};
assert!(
label.starts_with(matched::OPTIMIZER_RULE_FAILED),
"DataFusion's label for a failed optimizer rule changed; update \
matched::OPTIMIZER_RULE_FAILED: {label}"
);
assert_eq!(user_message(&err), "the cause");
}
#[tokio::test]
async fn datafusion_still_returns_syntax_errors_typed() {
let err = SessionContext::new()
.sql("SELEC 1")
.await
.expect_err("a syntax error");
assert!(
matches!(err.find_root(), DataFusionError::SQL(..)),
"DataFusion no longer returns a syntax error as DataFusionError::SQL: {err:?}"
);
let message = user_message(&err);
assert!(
message.starts_with("syntax error: ") && !message.contains("ParserError"),
"{message}"
);
}
fn tokenizer_error(sql: &str) -> String {
Tokenizer::new(&GenericDialect {}, sql)
.tokenize()
.expect_err("the tokenizer fails")
.message
}
#[test]
fn sqlparser_still_says_unterminated_and_eof() {
for sql in ["SELECT 'abc", "SELECT 'it''s"] {
let message = tokenizer_error(sql);
assert!(
message.starts_with(matched::TOKENIZER_UNTERMINATED),
"sqlparser's message for an open string changed; update \
matched::TOKENIZER_UNTERMINATED: {sql}: {message}"
);
}
for sql in ["SELECT \"abc", "SELECT 1 /* a note"] {
let message = tokenizer_error(sql);
assert!(
message.contains(matched::TOKENIZER_EOF),
"sqlparser's message for an open quoted name or comment changed; update \
matched::TOKENIZER_EOF: {sql}: {message}"
);
}
}
#[test]
fn strips_variant_prefixes() {
let err = DataFusionError::Plan("table 'x' not found".into());
assert_eq!(user_message(&err), "table 'x' not found");
let err = DataFusionError::SQL(
Box::new(ParserError::ParserError("Expected: an expression".into())),
None,
);
assert_eq!(user_message(&err), "syntax error: Expected: an expression");
let err = DataFusionError::External(Box::new(DataFusionError::Execution("boom".into())));
assert_eq!(user_message(&err), "boom");
}
}