Skip to main content

datafusion_common/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! # Error Handling in DataFusion
6//!
7//! In DataFusion, there are two types of errors that can be raised:
8//!
9//! 1. Expected errors – These indicate invalid operations performed by the caller,
10//!    such as attempting to open a non-existent file. Different categories exist to
11//!    distinguish their sources (e.g., [`DataFusionError::ArrowError`],
12//!    [`DataFusionError::IoError`], etc.).
13//!
14//! 2. Unexpected errors – Represented by [`DataFusionError::Internal`], these
15//!    indicate that an internal invariant has been broken, suggesting a potential
16//!    bug in the system.
17//!
18//! There are several convenient macros for throwing errors. For example, use
19//! `exec_err!` for expected errors.
20//! For invariant checks, you can use `assert_or_internal_err!`,
21//! `assert_eq_or_internal_err!`, `assert_ne_or_internal_err!` for easier assertions.
22//! On the performance-critical path, use `debug_assert!` instead to reduce overhead.
23
24#[cfg(feature = "backtrace")]
25use std::backtrace::{Backtrace, BacktraceStatus};
26
27use std::borrow::Cow;
28use std::collections::VecDeque;
29use std::error::Error;
30use std::fmt::{Display, Formatter};
31use std::io;
32use std::result;
33use std::sync::Arc;
34
35use crate::utils::datafusion_strsim::{levenshtein_with_buffer, normalized_levenshtein};
36use crate::utils::quote_identifier;
37use crate::{Column, DFSchema, Diagnostic, TableReference};
38use arrow::error::ArrowError;
39#[cfg(feature = "parquet")]
40use parquet::errors::ParquetError;
41#[cfg(feature = "sql")]
42use sqlparser::parser::ParserError;
43use tokio::task::JoinError;
44
45/// Result type for operations that could result in an [DataFusionError]
46pub type Result<T, E = DataFusionError> = result::Result<T, E>;
47
48/// Result type for operations that could result in an [DataFusionError] and needs to be shared (wrapped into `Arc`).
49pub type SharedResult<T> = result::Result<T, Arc<DataFusionError>>;
50
51/// Error type for generic operations that could result in DataFusionError::External
52pub type GenericError = Box<dyn Error + Send + Sync>;
53
54/// DataFusion error
55#[derive(Debug)]
56pub enum DataFusionError {
57    /// Error returned by arrow.
58    ///
59    /// 2nd argument is for optional backtrace
60    ArrowError(Box<ArrowError>, Option<String>),
61    /// Error when reading / writing Parquet data.
62    #[cfg(feature = "parquet")]
63    ParquetError(Box<ParquetError>),
64    /// Error when reading / writing to / from an object_store (e.g. S3 or LocalFile)
65    #[cfg(feature = "object_store")]
66    ObjectStore(Box<object_store::Error>),
67    /// Error when an I/O operation fails
68    IoError(io::Error),
69    /// Error when SQL is syntactically incorrect.
70    ///
71    /// 2nd argument is for optional backtrace
72    #[cfg(feature = "sql")]
73    SQL(Box<ParserError>, Option<String>),
74    /// Error when a feature is not yet implemented.
75    ///
76    /// These errors are sometimes returned for features that are still in
77    /// development and are not entirely complete. Often, these errors are
78    /// tracked in our issue tracker.
79    NotImplemented(String),
80    /// Error due to bugs in DataFusion
81    ///
82    /// This error should not happen in normal usage of DataFusion. It results
83    /// from something that wasn't expected/anticipated by the implementation
84    /// and that is most likely a bug (the error message even encourages users
85    /// to open a bug report). A user should not be able to trigger internal
86    /// errors under normal circumstances by feeding in malformed queries, bad
87    /// data, etc.
88    ///
89    /// Note that I/O errors (or any error that happens due to external systems)
90    /// do NOT fall under this category. See other variants such as
91    /// [`Self::IoError`] and [`Self::External`].
92    ///
93    /// DataFusions has internal invariants that the compiler is not always able
94    /// to check. This error is raised when one of those invariants does not
95    /// hold for some reason.
96    Internal(String),
97    /// Error during planning of the query.
98    ///
99    /// This error happens when the user provides a bad query or plan, for
100    /// example the user attempts to call a function that doesn't exist, or if
101    /// the types of a function call are not supported.
102    Plan(String),
103    /// Error for invalid or unsupported configuration options.
104    Configuration(String),
105    /// Error when there is a problem with the query related to schema.
106    ///
107    /// This error can be returned in cases such as when schema inference is not
108    /// possible and when column names are not unique.
109    ///
110    /// 2nd argument is for optional backtrace
111    /// Boxing the optional backtrace to prevent <https://rust-lang.github.io/rust-clippy/master/index.html#/result_large_err>
112    SchemaError(Box<SchemaError>, Box<Option<String>>),
113    /// Error during execution of the query.
114    ///
115    /// This error is returned when an error happens during execution due to a
116    /// malformed input. For example, the user passed malformed arguments to a
117    /// SQL method, opened a CSV file that is broken, or tried to divide an
118    /// integer by zero.
119    Execution(String),
120    /// [`JoinError`] during execution of the query.
121    ///
122    /// This error can't occur for unjoined tasks, such as execution shutdown.
123    ExecutionJoin(Box<JoinError>),
124    /// Error when resources (such as memory of scratch disk space) are exhausted.
125    ///
126    /// This error is thrown when a consumer cannot acquire additional memory
127    /// or other resources needed to execute the query from the Memory Manager.
128    ResourcesExhausted(String),
129    /// Errors originating from outside DataFusion's core codebase.
130    ///
131    /// For example, a custom S3Error from the crate datafusion-objectstore-s3
132    External(GenericError),
133    /// Error with additional context
134    Context(String, Box<DataFusionError>),
135    /// Errors from either mapping LogicalPlans to/from Substrait plans
136    /// or serializing/deserializing protobytes to Substrait plans
137    Substrait(String),
138    /// Error wrapped together with additional contextual information intended
139    /// for end users, to help them understand what went wrong by providing
140    /// human-readable messages, and locations in the source query that relate
141    /// to the error in some way.
142    Diagnostic(Box<Diagnostic>, Box<DataFusionError>),
143    /// A collection of one or more [`DataFusionError`]. Useful in cases where
144    /// DataFusion can recover from an erroneous state, and produce more errors
145    /// before terminating. e.g. when planning a SELECT clause, DataFusion can
146    /// synchronize to the next `SelectItem` if the previous one had errors. The
147    /// end result is that the user can see errors about all `SelectItem`,
148    /// instead of just the first one.
149    Collection(Vec<DataFusionError>),
150    /// A [`DataFusionError`] which shares an underlying [`DataFusionError`].
151    ///
152    /// This is useful when the same underlying [`DataFusionError`] is passed
153    /// to multiple receivers. For example, when the source of a repartition
154    /// errors and the error is propagated to multiple consumers.
155    Shared(Arc<DataFusionError>),
156    /// An error that originated during a foreign function interface call.
157    /// Transferring errors across the FFI boundary is difficult, so the original
158    /// error will be converted to a string.
159    Ffi(String),
160}
161
162#[macro_export]
163macro_rules! context {
164    ($desc:expr, $err:expr) => {
165        $err.context(format!("{} at {}:{}", $desc, file!(), line!()))
166    };
167}
168
169/// Schema-related errors
170#[derive(Debug)]
171pub enum SchemaError {
172    /// Schema contains a (possibly) qualified and unqualified field with same unqualified name
173    AmbiguousReference { field: Box<Column> },
174    /// Schema contains duplicate qualified field name
175    DuplicateQualifiedField {
176        qualifier: Box<TableReference>,
177        name: String,
178    },
179    /// Schema contains duplicate unqualified field name
180    DuplicateUnqualifiedField { name: String },
181    /// No field with this name
182    FieldNotFound {
183        field: Box<Column>,
184        valid_fields: Vec<Column>,
185    },
186}
187
188fn case_insensitive_field_match<'a>(
189    field: &Column,
190    valid_fields: &'a [Column],
191) -> Option<&'a Column> {
192    let field_name = field.name();
193    let field_flat_name = field.flat_name();
194    let field_name_lower = field_name.to_lowercase();
195    let field_flat_name_lower = field_flat_name.to_lowercase();
196
197    valid_fields.iter().find(|valid_field| {
198        let valid_field_name = valid_field.name();
199        let valid_field_flat_name = valid_field.flat_name();
200        let valid_field_name_lower = valid_field_name.to_lowercase();
201        let valid_field_flat_name_lower = valid_field_flat_name.to_lowercase();
202
203        let name_differs_only_by_case =
204            field_name_lower == valid_field_name_lower && field_name != valid_field_name;
205        let flat_name_differs_only_by_case = field_flat_name_lower
206            == valid_field_flat_name_lower
207            && field_flat_name != valid_field_flat_name;
208
209        name_differs_only_by_case || flat_name_differs_only_by_case
210    })
211}
212
213/// Find the most similar field name based on edit distance.
214/// Returns `None` if all candidate edit distances are too far away.
215fn closest_valid_field<'a>(
216    field: &Column,
217    valid_fields: &'a [Column],
218) -> Option<&'a Column> {
219    // Find the most similar valid field name.
220    let target_names = [
221        field.name().to_lowercase(),
222        field.flat_name().to_lowercase(),
223    ];
224
225    let mut best_match: Option<(usize, usize, usize, &Column)> = None;
226    let mut cache = Vec::new();
227    for (index, valid_field) in valid_fields.iter().enumerate() {
228        let valid_names = [
229            valid_field.name().to_lowercase(),
230            valid_field.flat_name().to_lowercase(),
231        ];
232        for target in &target_names {
233            for valid_name in &valid_names {
234                let distance = levenshtein_with_buffer(target, valid_name, &mut cache);
235                let max_len = target.chars().count().max(valid_name.chars().count());
236                // If there are no shared characters, or we would have to edit
237                // more than half of the longer name, don't suggest a potential match.
238                if max_len == 0 || distance * 2 > max_len {
239                    continue;
240                }
241
242                let should_replace = best_match.is_none_or(
243                    |(best_distance, best_max_len, best_index, _)| {
244                        distance < best_distance
245                            || distance == best_distance
246                                && (max_len > best_max_len
247                                    || max_len == best_max_len && index < best_index)
248                    },
249                );
250                if should_replace {
251                    best_match = Some((distance, max_len, index, valid_field));
252                }
253            }
254        }
255    }
256
257    best_match.map(|(_, _, _, valid_field)| valid_field)
258}
259
260/// Maximum number of field names listed in a [`SchemaError::FieldNotFound`]
261/// message. Schemas with hundreds or thousands of columns are ordinary in
262/// analytics workloads, and listing all of them produced error messages
263/// thousands of characters long that pushed the actual error off screen.
264const MAX_LISTED_VALID_FIELDS: usize = 20;
265
266impl Display for SchemaError {
267    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
268        match self {
269            Self::FieldNotFound {
270                field,
271                valid_fields,
272            } => {
273                let closest_field = closest_valid_field(field, valid_fields);
274                let case_sensitive_match =
275                    case_insensitive_field_match(field, valid_fields);
276
277                write!(f, "No field named {}", field.quoted_flat_name())?;
278                if let Some(matched) = closest_field {
279                    write!(f, ". Did you mean '{}'?", matched.quoted_flat_name())?;
280                } else {
281                    write!(f, ".")?;
282                }
283
284                if let Some(case_sensitive_match) = case_sensitive_match {
285                    write!(
286                        f,
287                        "\nColumn names are case sensitive. You can use double quotes to refer to the {} column \
288                        or disable the datafusion.sql_parser.enable_ident_normalization configuration.",
289                        case_sensitive_match.quoted_flat_name()
290                    )?;
291                }
292
293                if !valid_fields.is_empty() {
294                    // Wide schemas are common, and listing every field turns a
295                    // one-line mistake into a screenful of output. The "Did you
296                    // mean" hint above is the actionable part; the list is just
297                    // context, so cap it.
298                    let listed = valid_fields
299                        .iter()
300                        .take(MAX_LISTED_VALID_FIELDS)
301                        .map(|field| field.quoted_flat_name())
302                        .collect::<Vec<String>>()
303                        .join(", ");
304                    match valid_fields.len().saturating_sub(MAX_LISTED_VALID_FIELDS) {
305                        0 => write!(f, "\nValid fields are {listed}."),
306                        remaining => write!(
307                            f,
308                            "\nValid fields are {listed} and {remaining} other{}.",
309                            if remaining == 1 { "" } else { "s" }
310                        ),
311                    }
312                } else {
313                    Ok(())
314                }
315            }
316            Self::DuplicateQualifiedField { qualifier, name } => {
317                write!(
318                    f,
319                    "Schema contains duplicate qualified field name {}.{}",
320                    qualifier.to_quoted_string(),
321                    quote_identifier(name)
322                )
323            }
324            Self::DuplicateUnqualifiedField { name } => {
325                write!(
326                    f,
327                    "Schema contains duplicate unqualified field name {}",
328                    quote_identifier(name)
329                )
330            }
331            Self::AmbiguousReference { field } => {
332                if field.relation.is_some() {
333                    write!(
334                        f,
335                        "Schema contains qualified field name {} and unqualified field name {} which would be ambiguous",
336                        field.quoted_flat_name(),
337                        quote_identifier(&field.name)
338                    )
339                } else {
340                    write!(
341                        f,
342                        "Ambiguous reference to unqualified field {}",
343                        field.quoted_flat_name()
344                    )
345                }
346            }
347        }
348    }
349}
350
351impl Error for SchemaError {}
352
353impl From<std::fmt::Error> for DataFusionError {
354    fn from(_e: std::fmt::Error) -> Self {
355        DataFusionError::Execution("Fail to format".to_string())
356    }
357}
358
359impl From<io::Error> for DataFusionError {
360    fn from(e: io::Error) -> Self {
361        DataFusionError::IoError(e)
362    }
363}
364
365impl From<ArrowError> for DataFusionError {
366    fn from(e: ArrowError) -> Self {
367        DataFusionError::ArrowError(Box::new(e), Some(DataFusionError::get_back_trace()))
368    }
369}
370
371impl From<DataFusionError> for ArrowError {
372    fn from(e: DataFusionError) -> Self {
373        match e {
374            DataFusionError::ArrowError(e, _) => *e,
375            DataFusionError::External(e) => ArrowError::ExternalError(e),
376            other => ArrowError::ExternalError(Box::new(other)),
377        }
378    }
379}
380
381impl From<&Arc<DataFusionError>> for DataFusionError {
382    fn from(e: &Arc<DataFusionError>) -> Self {
383        if let DataFusionError::Shared(e_inner) = e.as_ref() {
384            // don't re-wrap
385            DataFusionError::Shared(Arc::clone(e_inner))
386        } else {
387            DataFusionError::Shared(Arc::clone(e))
388        }
389    }
390}
391
392#[cfg(feature = "parquet")]
393impl From<ParquetError> for DataFusionError {
394    fn from(e: ParquetError) -> Self {
395        DataFusionError::ParquetError(Box::new(e))
396    }
397}
398
399#[cfg(feature = "object_store")]
400impl From<object_store::Error> for DataFusionError {
401    fn from(e: object_store::Error) -> Self {
402        DataFusionError::ObjectStore(Box::new(e))
403    }
404}
405
406#[cfg(feature = "object_store")]
407impl From<object_store::path::Error> for DataFusionError {
408    fn from(e: object_store::path::Error) -> Self {
409        DataFusionError::ObjectStore(Box::new(e.into()))
410    }
411}
412
413#[cfg(feature = "sql")]
414impl From<ParserError> for DataFusionError {
415    fn from(e: ParserError) -> Self {
416        DataFusionError::SQL(Box::new(e), None)
417    }
418}
419
420impl From<GenericError> for DataFusionError {
421    fn from(err: GenericError) -> Self {
422        // If the error is already a DataFusionError, not wrapping it.
423        if err.is::<DataFusionError>() {
424            if let Ok(e) = err.downcast::<DataFusionError>() {
425                *e
426            } else {
427                unreachable!()
428            }
429        } else {
430            DataFusionError::External(err)
431        }
432    }
433}
434
435impl Display for DataFusionError {
436    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
437        let error_prefix = self.error_prefix();
438        let message = self.message();
439        write!(f, "{error_prefix}{message}")
440    }
441}
442
443impl Error for DataFusionError {
444    fn source(&self) -> Option<&(dyn Error + 'static)> {
445        match self {
446            DataFusionError::ArrowError(e, _) => Some(e.as_ref()),
447            #[cfg(feature = "parquet")]
448            DataFusionError::ParquetError(e) => Some(e.as_ref()),
449            #[cfg(feature = "object_store")]
450            DataFusionError::ObjectStore(e) => Some(e.as_ref()),
451            DataFusionError::IoError(e) => Some(e),
452            #[cfg(feature = "sql")]
453            DataFusionError::SQL(e, _) => Some(e.as_ref()),
454            DataFusionError::NotImplemented(_) => None,
455            DataFusionError::Internal(_) => None,
456            DataFusionError::Configuration(_) => None,
457            DataFusionError::Plan(_) => None,
458            DataFusionError::SchemaError(e, _) => Some(e.as_ref()),
459            DataFusionError::Execution(_) => None,
460            DataFusionError::ExecutionJoin(e) => Some(e.as_ref()),
461            DataFusionError::ResourcesExhausted(_) => None,
462            DataFusionError::External(e) => Some(e.as_ref()),
463            DataFusionError::Context(_, e) => Some(e.as_ref()),
464            DataFusionError::Substrait(_) => None,
465            DataFusionError::Diagnostic(_, e) => Some(e.as_ref()),
466            // Can't really make a Collection fit into the mold of "an error has
467            // at most one source", but returning the first one is probably good
468            // idea. Especially since `DataFusionError::Collection` is mostly
469            // meant for consumption by the end user, so shouldn't interfere
470            // with programmatic usage too much. Plus, having 1 or 5 errors
471            // doesn't really change the fact that the query is invalid and
472            // can't be executed.
473            DataFusionError::Collection(errs) => errs.first().map(|e| e as &dyn Error),
474            DataFusionError::Shared(e) => Some(e.as_ref()),
475            DataFusionError::Ffi(_) => None,
476        }
477    }
478}
479
480impl From<DataFusionError> for io::Error {
481    fn from(e: DataFusionError) -> Self {
482        io::Error::other(e)
483    }
484}
485
486impl DataFusionError {
487    /// The separator between the error message and the backtrace
488    pub const BACK_TRACE_SEP: &'static str = "\n\nbacktrace: ";
489
490    /// Get deepest underlying [`DataFusionError`]
491    ///
492    /// [`DataFusionError`]s sometimes form a chain, such as `DataFusionError::ArrowError()` in order to conform
493    /// to the correct error signature. Thus sometimes there is a chain several layers deep that can obscure the
494    /// original error. This function finds the lowest level DataFusionError possible.
495    ///
496    /// For example,  `find_root` will return`DataFusionError::ResourceExhausted` given the input
497    /// ```text
498    /// DataFusionError::ArrowError
499    ///   ArrowError::External
500    ///    Box(DataFusionError::Context)
501    ///      DataFusionError::ResourceExhausted
502    /// ```
503    ///
504    /// This may be the same as `self`.
505    pub fn find_root(&self) -> &Self {
506        // Note: This is a non-recursive algorithm so we do not run
507        // out of stack space, even for long error chains.
508
509        let mut last_datafusion_error = self;
510        let mut root_error: &dyn Error = self;
511        while let Some(source) = root_error.source() {
512            // walk the next level
513            root_error = source;
514            // remember the lowest datafusion error so far
515            if let Some(e) = root_error.downcast_ref::<DataFusionError>() {
516                last_datafusion_error = e;
517            } else if let Some(e) = root_error.downcast_ref::<Arc<DataFusionError>>() {
518                // As `Arc<T>::source()` calls through to `T::source()` we need to
519                // explicitly match `Arc<DataFusionError>` to capture it
520                last_datafusion_error = e.as_ref();
521            }
522        }
523        // return last checkpoint (which may be the original error)
524        last_datafusion_error
525    }
526
527    /// wraps self in Self::Context with a description
528    pub fn context(self, description: impl Into<String>) -> Self {
529        Self::Context(description.into(), Box::new(self))
530    }
531
532    /// Strips backtrace out of the error message
533    /// If backtrace enabled then error has a format "message" [`Self::BACK_TRACE_SEP`] "backtrace"
534    /// The method strips the backtrace and outputs "message"
535    pub fn strip_backtrace(&self) -> String {
536        (*self
537            .to_string()
538            .split(Self::BACK_TRACE_SEP)
539            .collect::<Vec<&str>>()
540            .first()
541            .unwrap_or(&""))
542        .to_string()
543    }
544
545    /// To enable optional rust backtrace in DataFusion:
546    /// - [`Setup Env Variables`]<https://doc.rust-lang.org/std/backtrace/index.html#environment-variables>
547    /// - Enable `backtrace` cargo feature
548    ///
549    /// Example:
550    /// cargo build --features 'backtrace'
551    /// RUST_BACKTRACE=1 ./app
552    #[inline(always)]
553    pub fn get_back_trace() -> String {
554        #[cfg(feature = "backtrace")]
555        {
556            let back_trace = Backtrace::capture();
557            if back_trace.status() == BacktraceStatus::Captured {
558                return format!("{}{}", Self::BACK_TRACE_SEP, back_trace);
559            }
560
561            "".to_owned()
562        }
563
564        #[cfg(not(feature = "backtrace"))]
565        "".to_owned()
566    }
567
568    /// Return a [`DataFusionErrorBuilder`] to build a [`DataFusionError`]
569    pub fn builder() -> DataFusionErrorBuilder {
570        DataFusionErrorBuilder::default()
571    }
572
573    fn error_prefix(&self) -> &'static str {
574        match self {
575            DataFusionError::ArrowError(_, _) => "Arrow error: ",
576            #[cfg(feature = "parquet")]
577            DataFusionError::ParquetError(_) => "Parquet error: ",
578            #[cfg(feature = "object_store")]
579            DataFusionError::ObjectStore(_) => "Object Store error: ",
580            DataFusionError::IoError(_) => "IO error: ",
581            #[cfg(feature = "sql")]
582            DataFusionError::SQL(_, _) => "SQL error: ",
583            DataFusionError::NotImplemented(_) => {
584                "This feature is not implemented: "
585            }
586            DataFusionError::Internal(_) => "Internal error: ",
587            DataFusionError::Plan(_) => "Error during planning: ",
588            DataFusionError::Configuration(_) => {
589                "Invalid or Unsupported Configuration: "
590            }
591            DataFusionError::SchemaError(_, _) => "Schema error: ",
592            DataFusionError::Execution(_) => "Execution error: ",
593            DataFusionError::ExecutionJoin(_) => "ExecutionJoin error: ",
594            DataFusionError::ResourcesExhausted(_) => {
595                "Resources exhausted: "
596            }
597            DataFusionError::External(_) => "External error: ",
598            DataFusionError::Context(_, _) => "",
599            DataFusionError::Substrait(_) => "Substrait error: ",
600            DataFusionError::Diagnostic(_, _) => "",
601            DataFusionError::Collection(errs) => {
602                errs.first().expect("cannot construct DataFusionError::Collection with 0 errors, but got one such case").error_prefix()
603            }
604            DataFusionError::Shared(_) => "",
605            DataFusionError::Ffi(_) => "FFI error: ",
606        }
607    }
608
609    pub fn message(&self) -> Cow<'_, str> {
610        match *self {
611            DataFusionError::ArrowError(ref desc, ref backtrace) => {
612                let backtrace = backtrace.clone().unwrap_or_else(|| "".to_owned());
613                Cow::Owned(format!("{desc}{backtrace}"))
614            }
615            #[cfg(feature = "parquet")]
616            DataFusionError::ParquetError(ref desc) => Cow::Owned(desc.to_string()),
617            DataFusionError::IoError(ref desc) => Cow::Owned(desc.to_string()),
618            #[cfg(feature = "sql")]
619            DataFusionError::SQL(ref desc, ref backtrace) => {
620                let backtrace: String =
621                    backtrace.clone().unwrap_or_else(|| "".to_owned());
622                Cow::Owned(format!("{desc:?}{backtrace}"))
623            }
624            DataFusionError::Configuration(ref desc) => Cow::Owned(desc.to_string()),
625            DataFusionError::NotImplemented(ref desc) => Cow::Owned(desc.to_string()),
626            DataFusionError::Internal(ref desc) => Cow::Owned(format!(
627                "{desc}.\nThis issue was likely caused by a bug in DataFusion's code. \
628                Please help us to resolve this by filing a bug report in our issue tracker: \
629                https://github.com/apache/datafusion/issues"
630            )),
631            DataFusionError::Plan(ref desc) => Cow::Owned(desc.to_string()),
632            DataFusionError::SchemaError(ref desc, ref backtrace) => {
633                let backtrace: &str =
634                    &backtrace.as_ref().clone().unwrap_or_else(|| "".to_owned());
635                Cow::Owned(format!("{desc}{backtrace}"))
636            }
637            DataFusionError::Execution(ref desc) => Cow::Owned(desc.to_string()),
638            DataFusionError::ExecutionJoin(ref desc) => Cow::Owned(desc.to_string()),
639            DataFusionError::ResourcesExhausted(ref desc) => Cow::Owned(desc.to_string()),
640            DataFusionError::External(ref desc) => Cow::Owned(desc.to_string()),
641            #[cfg(feature = "object_store")]
642            DataFusionError::ObjectStore(ref desc) => Cow::Owned(desc.to_string()),
643            DataFusionError::Context(ref desc, ref err) => {
644                Cow::Owned(format!("{desc}\ncaused by\n{}", *err))
645            }
646            DataFusionError::Substrait(ref desc) => Cow::Owned(desc.to_string()),
647            DataFusionError::Diagnostic(_, ref err) => Cow::Owned(err.to_string()),
648            // Returning the message of the first error is probably fine enough,
649            // and makes `DataFusionError::Collection` a transparent wrapped,
650            // unless the end user explicitly calls `DataFusionError::iter`.
651            DataFusionError::Collection(ref errs) => errs
652                .first()
653                .expect("cannot construct DataFusionError::Collection with 0 errors")
654                .message(),
655            DataFusionError::Shared(ref desc) => Cow::Owned(desc.to_string()),
656            DataFusionError::Ffi(ref desc) => Cow::Owned(desc.to_string()),
657        }
658    }
659
660    /// Wraps the error with contextual information intended for end users
661    pub fn with_diagnostic(self, diagnostic: Diagnostic) -> Self {
662        Self::Diagnostic(Box::new(diagnostic), Box::new(self))
663    }
664
665    /// Wraps the error with contextual information intended for end users.
666    /// Takes a function that inspects the error and returns the diagnostic to
667    /// wrap it with.
668    pub fn with_diagnostic_fn<F: FnOnce(&DataFusionError) -> Diagnostic>(
669        self,
670        f: F,
671    ) -> Self {
672        let diagnostic = f(&self);
673        self.with_diagnostic(diagnostic)
674    }
675
676    /// Gets the [`Diagnostic`] associated with the error, if any. If there is
677    /// more than one, only the outermost [`Diagnostic`] is returned.
678    pub fn diagnostic(&self) -> Option<&Diagnostic> {
679        struct DiagnosticsIterator<'a> {
680            head: &'a DataFusionError,
681        }
682
683        impl<'a> Iterator for DiagnosticsIterator<'a> {
684            type Item = &'a Diagnostic;
685
686            fn next(&mut self) -> Option<Self::Item> {
687                loop {
688                    if let DataFusionError::Diagnostic(diagnostics, source) = self.head {
689                        self.head = source.as_ref();
690                        return Some(diagnostics);
691                    }
692
693                    {
694                        let source = self.head.source().and_then(|source| {
695                            source.downcast_ref::<DataFusionError>()
696                        })?;
697                        self.head = source;
698                    }
699                }
700            }
701        }
702
703        DiagnosticsIterator { head: self }.next()
704    }
705
706    /// Return an iterator over this [`DataFusionError`] and any other
707    /// [`DataFusionError`]s in a [`DataFusionError::Collection`].
708    ///
709    /// Sometimes DataFusion is able to collect multiple errors in a SQL query
710    /// before terminating, e.g. across different expressions in a SELECT
711    /// statements or different sides of a UNION. This method returns an
712    /// iterator over all the errors in the collection.
713    ///
714    /// For this to work, the top-level error must be a
715    /// `DataFusionError::Collection`, not something that contains it.
716    pub fn iter(&self) -> impl Iterator<Item = &DataFusionError> {
717        struct ErrorIterator<'a> {
718            queue: VecDeque<&'a DataFusionError>,
719        }
720
721        impl<'a> Iterator for ErrorIterator<'a> {
722            type Item = &'a DataFusionError;
723
724            fn next(&mut self) -> Option<Self::Item> {
725                loop {
726                    let popped = self.queue.pop_front()?;
727                    match popped {
728                        DataFusionError::Collection(errs) => self.queue.extend(errs),
729                        _ => return Some(popped),
730                    }
731                }
732            }
733        }
734
735        let mut queue = VecDeque::new();
736        queue.push_back(self);
737        ErrorIterator { queue }
738    }
739}
740
741/// A builder for [`DataFusionError`]
742///
743/// This builder can be used to collect multiple errors and return them as a
744/// [`DataFusionError::Collection`].
745///
746/// # Example: no errors
747/// ```
748/// # use datafusion_common::DataFusionError;
749/// let mut builder = DataFusionError::builder();
750/// // ok_or returns the value if no errors have been added
751/// assert_eq!(builder.error_or(42).unwrap(), 42);
752/// ```
753///
754/// # Example: with errors
755/// ```
756/// # use datafusion_common::{assert_contains, DataFusionError};
757/// let mut builder = DataFusionError::builder();
758/// builder.add_error(DataFusionError::Internal("foo".to_owned()));
759/// // ok_or returns the value if no errors have been added
760/// assert_contains!(
761///     builder.error_or(42).unwrap_err().to_string(),
762///     "Internal error: foo"
763/// );
764/// ```
765#[derive(Debug, Default)]
766pub struct DataFusionErrorBuilder(Vec<DataFusionError>);
767
768impl DataFusionErrorBuilder {
769    /// Create a new [`DataFusionErrorBuilder`]
770    pub fn new() -> Self {
771        Default::default()
772    }
773
774    /// Add an error to the in progress list
775    ///
776    /// # Example
777    /// ```
778    /// # use datafusion_common::{assert_contains, DataFusionError};
779    /// let mut builder = DataFusionError::builder();
780    /// builder.add_error(DataFusionError::Internal("foo".to_owned()));
781    /// assert_contains!(
782    ///     builder.error_or(42).unwrap_err().to_string(),
783    ///     "Internal error: foo"
784    /// );
785    /// ```
786    pub fn add_error(&mut self, error: DataFusionError) {
787        self.0.push(error);
788    }
789
790    /// Add an error to the in progress list, returning the builder
791    ///
792    /// # Example
793    /// ```
794    /// # use datafusion_common::{assert_contains, DataFusionError};
795    /// let builder = DataFusionError::builder()
796    ///     .with_error(DataFusionError::Internal("foo".to_owned()));
797    /// assert_contains!(
798    ///     builder.error_or(42).unwrap_err().to_string(),
799    ///     "Internal error: foo"
800    /// );
801    /// ```
802    pub fn with_error(mut self, error: DataFusionError) -> Self {
803        self.0.push(error);
804        self
805    }
806
807    /// Returns `Ok(ok)` if no errors were added to the builder,
808    /// otherwise returns a `Result::Err`
809    pub fn error_or<T>(self, ok: T) -> Result<T, DataFusionError> {
810        match self.0.len() {
811            0 => Ok(ok),
812            1 => Err(self.0.into_iter().next().expect("length matched 1")),
813            _ => Err(DataFusionError::Collection(self.0)),
814        }
815    }
816}
817
818/// Unwrap an `Option` if possible. Otherwise return an `DataFusionError::Internal`.
819/// In normal usage of DataFusion the unwrap should always succeed.
820///
821/// Example: `let values = unwrap_or_internal_err!(values)`
822#[macro_export]
823macro_rules! unwrap_or_internal_err {
824    ($Value: ident) => {
825        $Value.ok_or_else(|| {
826            $crate::error::_internal_datafusion_err!(
827                "{} should not be None",
828                stringify!($Value)
829            )
830        })?
831    };
832}
833
834/// Assert a condition, returning `DataFusionError::Internal` on failure.
835///
836/// # Examples
837///
838/// ```text
839/// assert_or_internal_err!(predicate);
840/// assert_or_internal_err!(predicate, "human readable message");
841/// assert_or_internal_err!(predicate, format!("details: {}", value));
842/// ```
843#[macro_export]
844macro_rules! assert_or_internal_err {
845    ($cond:expr) => {
846        if !$cond {
847            return Err($crate::error::_internal_datafusion_err!(
848                "Assertion failed: {}",
849                stringify!($cond)
850            ));
851        }
852    };
853    ($cond:expr, $($arg:tt)+) => {
854        if !$cond {
855            return Err($crate::error::_internal_datafusion_err!(
856                "Assertion failed: {}: {}",
857                stringify!($cond),
858                format!($($arg)+)
859            ));
860        }
861    };
862}
863
864/// Assert equality, returning `DataFusionError::Internal` on failure.
865///
866/// # Examples
867///
868/// ```text
869/// assert_eq_or_internal_err!(actual, expected);
870/// assert_eq_or_internal_err!(left_expr, right_expr, "values must match");
871/// assert_eq_or_internal_err!(lhs, rhs, "metadata: {}", extra);
872/// ```
873#[macro_export]
874macro_rules! assert_eq_or_internal_err {
875    ($left:expr, $right:expr $(,)?) => {{
876        let left_val = &$left;
877        let right_val = &$right;
878        if left_val != right_val {
879            return Err($crate::error::_internal_datafusion_err!(
880                "Assertion failed: {} == {} (left: {:?}, right: {:?})",
881                stringify!($left),
882                stringify!($right),
883                left_val,
884                right_val
885            ));
886        }
887    }};
888    ($left:expr, $right:expr, $($arg:tt)+) => {{
889        let left_val = &$left;
890        let right_val = &$right;
891        if left_val != right_val {
892            return Err($crate::error::_internal_datafusion_err!(
893                "Assertion failed: {} == {} (left: {:?}, right: {:?}): {}",
894                stringify!($left),
895                stringify!($right),
896                left_val,
897                right_val,
898                format!($($arg)+)
899            ));
900        }
901    }};
902}
903
904/// Assert inequality, returning `DataFusionError::Internal` on failure.
905///
906/// # Examples
907///
908/// ```text
909/// assert_ne_or_internal_err!(left, right);
910/// assert_ne_or_internal_err!(lhs_expr, rhs_expr, "values must differ");
911/// assert_ne_or_internal_err!(a, b, "context {}", info);
912/// ```
913#[macro_export]
914macro_rules! assert_ne_or_internal_err {
915    ($left:expr, $right:expr $(,)?) => {{
916        let left_val = &$left;
917        let right_val = &$right;
918        if left_val == right_val {
919            return Err($crate::error::_internal_datafusion_err!(
920                "Assertion failed: {} != {} (left: {:?}, right: {:?})",
921                stringify!($left),
922                stringify!($right),
923                left_val,
924                right_val
925            ));
926        }
927    }};
928    ($left:expr, $right:expr, $($arg:tt)+) => {{
929        let left_val = &$left;
930        let right_val = &$right;
931        if left_val == right_val {
932            return Err($crate::error::_internal_datafusion_err!(
933                "Assertion failed: {} != {} (left: {:?}, right: {:?}): {}",
934                stringify!($left),
935                stringify!($right),
936                left_val,
937                right_val,
938                format!($($arg)+)
939            ));
940        }
941    }};
942}
943
944/// Add a macros for concise  DataFusionError::* errors declaration
945/// supports placeholders the same way as `format!`
946/// Examples:
947///     plan_err!("Error")
948///     plan_err!("Error {}", val)
949///     plan_err!("Error {:?}", val)
950///     plan_err!("Error {val}")
951///     plan_err!("Error {val:?}")
952///
953/// `NAME_ERR` -  macro name for wrapping Err(DataFusionError::*)
954/// `PREFIXED_NAME_ERR` - underscore-prefixed alias for NAME_ERR (e.g., _plan_err)
955/// (Needed to avoid compiler error when using macro in the same crate: `macros from the current crate cannot be referred to by absolute paths`)
956/// `NAME_DF_ERR` -  macro name for wrapping DataFusionError::*. Needed to keep backtrace opportunity
957/// in construction where DataFusionError::* used directly, like `map_err`, `ok_or_else`, etc
958/// `PREFIXED_NAME_DF_ERR` - underscore-prefixed alias for NAME_DF_ERR (e.g., _plan_datafusion_err).
959/// (Needed to avoid compiler error when using macro in the same crate: `macros from the current crate cannot be referred to by absolute paths`)
960macro_rules! make_error {
961    ($NAME_ERR:ident, $PREFIXED_NAME_ERR:ident, $NAME_DF_ERR:ident, $PREFIXED_NAME_DF_ERR:ident, $ERR:ident) => {
962        make_error!(@inner ($), $NAME_ERR, $PREFIXED_NAME_ERR, $NAME_DF_ERR, $PREFIXED_NAME_DF_ERR, $ERR);
963    };
964    (@inner ($d:tt), $NAME_ERR:ident, $PREFIXED_NAME_ERR:ident, $NAME_DF_ERR:ident, $PREFIXED_NAME_DF_ERR:ident, $ERR:ident) => {
965        /// Macro wraps `$ERR` to add backtrace feature
966        #[macro_export]
967        macro_rules! $NAME_DF_ERR {
968            ($d($d args:expr),* $d(; diagnostic = $d DIAG:expr)?) => {{
969                let err = $crate::DataFusionError::$ERR(
970                    ::std::format!(
971                        "{}{}",
972                        ::std::format!($d($d args),*),
973                        $crate::DataFusionError::get_back_trace(),
974                    ).into()
975                );
976                $d (
977                    let err = err.with_diagnostic($d DIAG);
978                )?
979                err
980            }}
981        }
982
983        /// Macro wraps Err(`$ERR`) to add backtrace feature
984        #[macro_export]
985        macro_rules! $NAME_ERR {
986            ($d($d args:expr),* $d(; diagnostic = $d DIAG:expr)?) => {{
987                let err = $crate::$PREFIXED_NAME_DF_ERR!($d($d args),*);
988                $d (
989                    let err = err.with_diagnostic($d DIAG);
990                )?
991                Err(err)
992            }}
993        }
994
995        #[doc(hidden)]
996        pub use $NAME_ERR as $PREFIXED_NAME_ERR;
997        #[doc(hidden)]
998        pub use $NAME_DF_ERR as $PREFIXED_NAME_DF_ERR;
999    };
1000}
1001
1002// Exposes a macro to create `DataFusionError::Plan` with optional backtrace
1003make_error!(
1004    plan_err,
1005    _plan_err,
1006    plan_datafusion_err,
1007    _plan_datafusion_err,
1008    Plan
1009);
1010
1011// Exposes a macro to create `DataFusionError::Internal` with optional backtrace
1012make_error!(
1013    internal_err,
1014    _internal_err,
1015    internal_datafusion_err,
1016    _internal_datafusion_err,
1017    Internal
1018);
1019
1020// Exposes a macro to create `DataFusionError::NotImplemented` with optional backtrace
1021make_error!(
1022    not_impl_err,
1023    _not_impl_err,
1024    not_impl_datafusion_err,
1025    _not_impl_datafusion_err,
1026    NotImplemented
1027);
1028
1029// Exposes a macro to create `DataFusionError::Execution` with optional backtrace
1030make_error!(
1031    exec_err,
1032    _exec_err,
1033    exec_datafusion_err,
1034    _exec_datafusion_err,
1035    Execution
1036);
1037
1038// Exposes a macro to create `DataFusionError::Configuration` with optional backtrace
1039make_error!(
1040    config_err,
1041    _config_err,
1042    config_datafusion_err,
1043    _config_datafusion_err,
1044    Configuration
1045);
1046
1047// Exposes a macro to create `DataFusionError::Substrait` with optional backtrace
1048make_error!(
1049    substrait_err,
1050    _substrait_err,
1051    substrait_datafusion_err,
1052    _substrait_datafusion_err,
1053    Substrait
1054);
1055
1056// Exposes a macro to create `DataFusionError::ResourcesExhausted` with optional backtrace
1057make_error!(
1058    resources_err,
1059    _resources_err,
1060    resources_datafusion_err,
1061    _resources_datafusion_err,
1062    ResourcesExhausted
1063);
1064
1065// Exposes a macro to create `DataFusionError::Ffi` with optional backtrace
1066make_error!(
1067    ffi_err,
1068    _ffi_err,
1069    ffi_datafusion_err,
1070    _ffi_datafusion_err,
1071    Ffi
1072);
1073
1074// Exposes a macro to create `DataFusionError::SQL` with optional backtrace
1075#[macro_export]
1076macro_rules! sql_datafusion_err {
1077    ($ERR:expr $(; diagnostic = $DIAG:expr)?) => {{
1078        let err = $crate::DataFusionError::SQL(Box::new($ERR), Some($crate::DataFusionError::get_back_trace()));
1079        $(
1080            let err = err.with_diagnostic($DIAG);
1081        )?
1082        err
1083    }};
1084}
1085
1086// Exposes a macro to create `Err(DataFusionError::SQL)` with optional backtrace
1087#[macro_export]
1088macro_rules! sql_err {
1089    ($ERR:expr $(; diagnostic = $DIAG:expr)?) => {{
1090        let err = $crate::sql_datafusion_err!($ERR);
1091        $(
1092            let err = err.with_diagnostic($DIAG);
1093        )?
1094        Err(err)
1095    }};
1096}
1097
1098// Exposes a macro to create `DataFusionError::ArrowError` with optional backtrace
1099#[macro_export]
1100macro_rules! arrow_datafusion_err {
1101    ($ERR:expr $(; diagnostic = $DIAG:expr)?) => {{
1102        let err = $crate::DataFusionError::ArrowError(Box::new($ERR), Some($crate::DataFusionError::get_back_trace()));
1103        $(
1104            let err = err.with_diagnostic($DIAG);
1105        )?
1106        err
1107    }};
1108}
1109
1110// Exposes a macro to create `Err(DataFusionError::ArrowError)` with optional backtrace
1111#[macro_export]
1112macro_rules! arrow_err {
1113    ($ERR:expr $(; diagnostic = $DIAG:expr)?) => {
1114    {
1115        let err = $crate::arrow_datafusion_err!($ERR);
1116        $(
1117            let err = err.with_diagnostic($DIAG);
1118        )?
1119        Err(err)
1120    }};
1121}
1122
1123// Exposes a macro to create `DataFusionError::SchemaError` with optional backtrace
1124#[macro_export]
1125macro_rules! schema_datafusion_err {
1126    ($ERR:expr $(; diagnostic = $DIAG:expr)?) => {{
1127        let err = $crate::DataFusionError::SchemaError(
1128            Box::new($ERR),
1129            Box::new(Some($crate::DataFusionError::get_back_trace())),
1130        );
1131        $(
1132            let err = err.with_diagnostic($DIAG);
1133        )?
1134        err
1135    }};
1136}
1137
1138// Exposes a macro to create `Err(DataFusionError::SchemaError)` with optional backtrace
1139#[macro_export]
1140macro_rules! schema_err {
1141    ($ERR:expr $(; diagnostic = $DIAG:expr)?) => {{
1142        let err = $crate::DataFusionError::SchemaError(
1143            Box::new($ERR),
1144            Box::new(Some($crate::DataFusionError::get_back_trace())),
1145        );
1146        $(
1147            let err = err.with_diagnostic($DIAG);
1148        )?
1149        Err(err)
1150    }
1151    };
1152}
1153
1154// To avoid compiler error when using macro in the same crate:
1155// macros from the current crate cannot be referred to by absolute paths
1156pub use schema_err as _schema_err;
1157
1158/// Create a "field not found" DataFusion::SchemaError
1159pub fn field_not_found<R: Into<TableReference>>(
1160    qualifier: Option<R>,
1161    name: &str,
1162    schema: &DFSchema,
1163) -> DataFusionError {
1164    schema_datafusion_err!(SchemaError::FieldNotFound {
1165        field: Box::new(Column::new(qualifier, name)),
1166        valid_fields: schema.columns().to_vec(),
1167    })
1168}
1169
1170/// Convenience wrapper over [`field_not_found`] for when there is no qualifier
1171pub fn unqualified_field_not_found(name: &str, schema: &DFSchema) -> DataFusionError {
1172    schema_datafusion_err!(SchemaError::FieldNotFound {
1173        field: Box::new(Column::new_unqualified(name)),
1174        valid_fields: schema.columns().to_vec(),
1175    })
1176}
1177
1178pub fn add_possible_columns_to_diag(
1179    diagnostic: &mut Diagnostic,
1180    field: &Column,
1181    valid_fields: &[Column],
1182) {
1183    let field_names: Vec<String> = valid_fields
1184        .iter()
1185        .filter_map(|f| {
1186            if normalized_levenshtein(f.name(), field.name()) >= 0.5 {
1187                Some(f.flat_name())
1188            } else {
1189                None
1190            }
1191        })
1192        .collect();
1193
1194    for name in field_names {
1195        diagnostic.add_note(format!("possible column {name}"), None);
1196    }
1197}
1198
1199#[cfg(test)]
1200mod test {
1201    use super::*;
1202
1203    use std::mem::size_of;
1204    use std::sync::Arc;
1205
1206    use arrow::error::ArrowError;
1207    use insta::assert_snapshot;
1208
1209    fn field_not_found_message(num_fields: usize) -> String {
1210        let valid_fields = (0..num_fields)
1211            .map(|i| Column::new_unqualified(format!("col_{i}")))
1212            .collect::<Vec<_>>();
1213        SchemaError::FieldNotFound {
1214            field: Box::new(Column::new_unqualified("nope")),
1215            valid_fields,
1216        }
1217        .to_string()
1218    }
1219
1220    #[test]
1221    fn field_not_found_lists_every_field_for_a_narrow_schema() {
1222        assert_snapshot!(field_not_found_message(3), @r"
1223        No field named nope.
1224        Valid fields are col_0, col_1, col_2.
1225        ");
1226    }
1227
1228    #[test]
1229    fn field_not_found_lists_every_field_at_the_cap() {
1230        assert_snapshot!(field_not_found_message(MAX_LISTED_VALID_FIELDS), @r"
1231        No field named nope.
1232        Valid fields are col_0, col_1, col_2, col_3, col_4, col_5, col_6, col_7, col_8, col_9, col_10, col_11, col_12, col_13, col_14, col_15, col_16, col_17, col_18, col_19.
1233        ");
1234    }
1235
1236    #[test]
1237    fn field_not_found_uses_singular_for_one_extra_field() {
1238        assert_snapshot!(field_not_found_message(MAX_LISTED_VALID_FIELDS + 1), @r"
1239        No field named nope.
1240        Valid fields are col_0, col_1, col_2, col_3, col_4, col_5, col_6, col_7, col_8, col_9, col_10, col_11, col_12, col_13, col_14, col_15, col_16, col_17, col_18, col_19 and 1 other.
1241        ");
1242    }
1243
1244    /// A 200 column schema used to produce roughly 2.8k characters.
1245    #[test]
1246    fn field_not_found_truncates_a_wide_schema() {
1247        assert_snapshot!(field_not_found_message(200), @r"
1248        No field named nope.
1249        Valid fields are col_0, col_1, col_2, col_3, col_4, col_5, col_6, col_7, col_8, col_9, col_10, col_11, col_12, col_13, col_14, col_15, col_16, col_17, col_18, col_19 and 180 others.
1250        ");
1251    }
1252
1253    fn ok_result() -> Result<()> {
1254        Ok(())
1255    }
1256
1257    #[test]
1258    fn test_assert_eq_or_internal_err_passes() -> Result<()> {
1259        assert_eq_or_internal_err!(1, 1);
1260        ok_result()
1261    }
1262
1263    #[test]
1264    fn test_assert_eq_or_internal_err_fails() {
1265        fn check() -> Result<()> {
1266            assert_eq_or_internal_err!(1, 2, "expected equality");
1267            ok_result()
1268        }
1269
1270        let err = check().unwrap_err().strip_backtrace();
1271        assert!(err.starts_with("Internal error: Assertion failed: 1 == 2 (left: 1, right: 2): expected equality"));
1272    }
1273
1274    #[test]
1275    fn test_assert_ne_or_internal_err_passes() -> Result<()> {
1276        assert_ne_or_internal_err!(1, 2);
1277        ok_result()
1278    }
1279
1280    #[test]
1281    fn test_assert_ne_or_internal_err_fails() {
1282        fn check() -> Result<()> {
1283            assert_ne_or_internal_err!(3, 3, "values must differ");
1284            ok_result()
1285        }
1286
1287        let err = check().unwrap_err().strip_backtrace();
1288        assert!(err.starts_with("Internal error: Assertion failed: 3 != 3 (left: 3, right: 3): values must differ"));
1289    }
1290
1291    #[test]
1292    fn test_assert_or_internal_err_passes() -> Result<()> {
1293        assert_or_internal_err!(true);
1294        assert_or_internal_err!(true, "message");
1295        ok_result()
1296    }
1297
1298    #[test]
1299    fn test_assert_or_internal_err_fails_default() {
1300        fn check() -> Result<()> {
1301            assert_or_internal_err!(false);
1302            ok_result()
1303        }
1304
1305        let err = check().unwrap_err().strip_backtrace();
1306        assert!(err.starts_with("Internal error: Assertion failed: false"));
1307    }
1308
1309    #[test]
1310    fn test_assert_or_internal_err_fails_with_message() {
1311        fn check() -> Result<()> {
1312            assert_or_internal_err!(false, "custom message");
1313            ok_result()
1314        }
1315
1316        let err = check().unwrap_err().strip_backtrace();
1317        assert!(
1318            err.starts_with("Internal error: Assertion failed: false: custom message")
1319        );
1320    }
1321
1322    #[test]
1323    fn test_assert_or_internal_err_with_format_arguments() {
1324        fn check() -> Result<()> {
1325            assert_or_internal_err!(false, "custom {}", 42);
1326            ok_result()
1327        }
1328
1329        let err = check().unwrap_err().strip_backtrace();
1330        assert!(err.starts_with("Internal error: Assertion failed: false: custom 42"));
1331    }
1332
1333    #[test]
1334    fn test_error_size() {
1335        // Since Errors influence the size of Result which influence the size of the stack
1336        // please don't allow this to grow larger
1337        assert_eq!(size_of::<SchemaError>(), 40);
1338        assert_eq!(size_of::<DataFusionError>(), 40);
1339    }
1340
1341    #[test]
1342    fn datafusion_error_to_arrow() {
1343        let res = return_arrow_error().unwrap_err();
1344        assert!(
1345            res.to_string()
1346                .starts_with("External error: Error during planning: foo")
1347        );
1348    }
1349
1350    #[test]
1351    fn arrow_error_to_datafusion() {
1352        let res = return_datafusion_error().unwrap_err();
1353        assert_eq!(res.strip_backtrace(), "Arrow error: Schema error: bar");
1354    }
1355
1356    // To pass the test the environment variable RUST_BACKTRACE should be set to 1 to enforce backtrace
1357    #[cfg(feature = "backtrace")]
1358    fn ensure_rust_backtrace_enabled() {
1359        match std::env::var("RUST_BACKTRACE") {
1360            Ok(val) if val == "1" => {}
1361            _ => panic!("Environment variable RUST_BACKTRACE must be set to 1"),
1362        }
1363    }
1364
1365    // To pass the test the environment variable RUST_BACKTRACE should be set to 1 to enforce backtrace
1366    #[cfg(feature = "backtrace")]
1367    #[test]
1368    fn test_enabled_backtrace() {
1369        ensure_rust_backtrace_enabled();
1370
1371        let res: Result<(), DataFusionError> = plan_err!("Err");
1372        assert_error_have_message_and_backtrace(
1373            &res.unwrap_err(),
1374            "Error during planning: Err",
1375        );
1376    }
1377
1378    #[cfg(not(feature = "backtrace"))]
1379    #[test]
1380    fn test_disabled_backtrace() {
1381        let res: Result<(), DataFusionError> = plan_err!("Err");
1382        assert_err_without_backtrace_and_equal(
1383            &res.unwrap_err(),
1384            "Error during planning: Err",
1385        );
1386    }
1387
1388    #[cfg(not(feature = "backtrace"))]
1389    fn assert_err_without_backtrace_and_equal(
1390        err: &DataFusionError,
1391        expected_message: &str,
1392    ) {
1393        let err = err.to_string();
1394        assert!(!err.contains(DataFusionError::BACK_TRACE_SEP));
1395        assert_eq!(err, expected_message);
1396    }
1397
1398    #[cfg(not(feature = "backtrace"))]
1399    fn assert_internal_err_without_backtrace_and_equal(
1400        err: &DataFusionError,
1401        expected_message: &str,
1402    ) {
1403        let expected_message_before_backtrace = format!(
1404            "{expected_message}.\nThis issue was likely caused by a bug in DataFusion's code. \
1405                    Please help us to resolve this by filing a bug report in our issue tracker: \
1406                    https://github.com/apache/datafusion/issues"
1407        );
1408        assert_err_without_backtrace_and_equal(
1409            err,
1410            expected_message_before_backtrace.as_str(),
1411        );
1412    }
1413
1414    #[cfg(feature = "backtrace")]
1415    fn assert_error_have_message_and_backtrace(
1416        err: &DataFusionError,
1417        message_before_backtrace: &str,
1418    ) {
1419        let err = err.to_string();
1420        assert!(err.contains(DataFusionError::BACK_TRACE_SEP));
1421        assert!(
1422            !err.split(DataFusionError::BACK_TRACE_SEP)
1423                .collect::<Vec<&str>>()
1424                .get(1)
1425                .unwrap()
1426                .is_empty()
1427        );
1428        assert_eq!(
1429            err.split(DataFusionError::BACK_TRACE_SEP)
1430                .collect::<Vec<&str>>()
1431                .first()
1432                .copied()
1433                .unwrap(),
1434            message_before_backtrace,
1435            "full error is: {err}"
1436        );
1437    }
1438
1439    #[cfg(feature = "backtrace")]
1440    #[test]
1441    fn test_enabled_backtrace_for_unwrap_or_internal_err() {
1442        ensure_rust_backtrace_enabled();
1443
1444        fn get_error() -> Result<(), DataFusionError> {
1445            let item = None::<()>;
1446            unwrap_or_internal_err!(item);
1447
1448            unreachable!("should return error");
1449        }
1450
1451        let res: Result<(), DataFusionError> = get_error();
1452        assert_error_have_message_and_backtrace(
1453            &res.unwrap_err(),
1454            "Internal error: item should not be None",
1455        );
1456    }
1457
1458    // To pass the test the environment variable RUST_BACKTRACE should be set to 1 to enforce backtrace
1459    #[cfg(not(feature = "backtrace"))]
1460    #[test]
1461    fn test_disabled_backtrace_for_unwrap_or_internal_err() {
1462        fn get_error() -> Result<(), DataFusionError> {
1463            let item = None::<()>;
1464            unwrap_or_internal_err!(item);
1465
1466            unreachable!("should return error");
1467        }
1468
1469        let res: Result<(), DataFusionError> = get_error();
1470        assert_internal_err_without_backtrace_and_equal(
1471            &res.unwrap_err(),
1472            "Internal error: item should not be None",
1473        );
1474    }
1475
1476    #[cfg(feature = "backtrace")]
1477    #[test]
1478    fn test_enabled_backtrace_for_assert_or_internal_err_without_args() {
1479        ensure_rust_backtrace_enabled();
1480
1481        fn get_error() -> Result<(), DataFusionError> {
1482            assert_or_internal_err!(false);
1483
1484            unreachable!("should return error");
1485        }
1486
1487        let res: Result<(), DataFusionError> = get_error();
1488        assert_error_have_message_and_backtrace(
1489            &res.unwrap_err(),
1490            "Internal error: Assertion failed: false",
1491        );
1492    }
1493
1494    #[cfg(feature = "backtrace")]
1495    #[test]
1496    fn test_enabled_backtrace_for_assert_or_internal_err_with_args() {
1497        ensure_rust_backtrace_enabled();
1498
1499        fn get_error() -> Result<(), DataFusionError> {
1500            assert_or_internal_err!(false, "my cool context");
1501
1502            unreachable!("should return error");
1503        }
1504
1505        let res: Result<(), DataFusionError> = get_error();
1506        assert_error_have_message_and_backtrace(
1507            &res.unwrap_err(),
1508            "Internal error: Assertion failed: false: my cool context",
1509        );
1510    }
1511
1512    #[cfg(not(feature = "backtrace"))]
1513    #[test]
1514    fn test_disabled_backtrace_for_assert_or_internal_err_without_args() {
1515        fn get_error() -> Result<(), DataFusionError> {
1516            assert_or_internal_err!(false);
1517
1518            unreachable!("should return error");
1519        }
1520
1521        let res: Result<(), DataFusionError> = get_error();
1522        assert_internal_err_without_backtrace_and_equal(
1523            &res.unwrap_err(),
1524            "Internal error: Assertion failed: false",
1525        );
1526    }
1527
1528    #[cfg(not(feature = "backtrace"))]
1529    #[test]
1530    fn test_disabled_backtrace_for_assert_or_internal_err_with_args() {
1531        fn get_error() -> Result<(), DataFusionError> {
1532            assert_or_internal_err!(false, "my cool context");
1533
1534            unreachable!("should return error");
1535        }
1536
1537        let res: Result<(), DataFusionError> = get_error();
1538        assert_internal_err_without_backtrace_and_equal(
1539            &res.unwrap_err(),
1540            "Internal error: Assertion failed: false: my cool context",
1541        );
1542    }
1543
1544    #[cfg(feature = "backtrace")]
1545    #[test]
1546    fn test_enabled_backtrace_for_assert_eq_or_internal_err_without_args() {
1547        ensure_rust_backtrace_enabled();
1548
1549        fn get_error() -> Result<(), DataFusionError> {
1550            let arg1 = 1;
1551            let arg2 = 2;
1552            assert_eq_or_internal_err!(arg1, arg2);
1553
1554            unreachable!("should return error");
1555        }
1556
1557        let res: Result<(), DataFusionError> = get_error();
1558        assert_error_have_message_and_backtrace(
1559            &res.unwrap_err(),
1560            "Internal error: Assertion failed: arg1 == arg2 (left: 1, right: 2)",
1561        );
1562    }
1563
1564    #[cfg(feature = "backtrace")]
1565    #[test]
1566    fn test_enabled_backtrace_for_assert_eq_or_internal_err_with_args() {
1567        ensure_rust_backtrace_enabled();
1568
1569        fn get_error() -> Result<(), DataFusionError> {
1570            let arg1 = 1;
1571            let arg2 = 2;
1572            assert_eq_or_internal_err!(arg1, arg2, "my cool context");
1573
1574            unreachable!("should return error");
1575        }
1576
1577        let res: Result<(), DataFusionError> = get_error();
1578        assert_error_have_message_and_backtrace(
1579            &res.unwrap_err(),
1580            "Internal error: Assertion failed: arg1 == arg2 (left: 1, right: 2): my cool context",
1581        );
1582    }
1583
1584    #[cfg(not(feature = "backtrace"))]
1585    #[test]
1586    fn test_disabled_backtrace_for_assert_eq_or_internal_err_without_args() {
1587        fn get_error() -> Result<(), DataFusionError> {
1588            let arg1 = 1;
1589            let arg2 = 2;
1590            assert_eq_or_internal_err!(arg1, arg2);
1591
1592            unreachable!("should return error");
1593        }
1594
1595        let res: Result<(), DataFusionError> = get_error();
1596        assert_internal_err_without_backtrace_and_equal(
1597            &res.unwrap_err(),
1598            "Internal error: Assertion failed: arg1 == arg2 (left: 1, right: 2)",
1599        );
1600    }
1601
1602    #[cfg(not(feature = "backtrace"))]
1603    #[test]
1604    fn test_disabled_backtrace_for_assert_eq_or_internal_err_with_args() {
1605        fn get_error() -> Result<(), DataFusionError> {
1606            let arg1 = 1;
1607            let arg2 = 2;
1608            assert_eq_or_internal_err!(arg1, arg2, "my cool context");
1609
1610            unreachable!("should return error");
1611        }
1612
1613        let res: Result<(), DataFusionError> = get_error();
1614        assert_internal_err_without_backtrace_and_equal(
1615            &res.unwrap_err(),
1616            "Internal error: Assertion failed: arg1 == arg2 (left: 1, right: 2): my cool context",
1617        );
1618    }
1619
1620    #[cfg(feature = "backtrace")]
1621    #[test]
1622    fn test_enabled_backtrace_for_assert_ne_or_internal_err_without_args() {
1623        ensure_rust_backtrace_enabled();
1624
1625        fn get_error() -> Result<(), DataFusionError> {
1626            let arg1 = 1;
1627            let arg2 = 1;
1628            assert_ne_or_internal_err!(arg1, arg2);
1629
1630            unreachable!("should return error");
1631        }
1632
1633        let res: Result<(), DataFusionError> = get_error();
1634        assert_error_have_message_and_backtrace(
1635            &res.unwrap_err(),
1636            "Internal error: Assertion failed: arg1 != arg2 (left: 1, right: 1)",
1637        );
1638    }
1639
1640    #[cfg(feature = "backtrace")]
1641    #[test]
1642    fn test_enabled_backtrace_for_assert_ne_or_internal_err_with_args() {
1643        ensure_rust_backtrace_enabled();
1644
1645        fn get_error() -> Result<(), DataFusionError> {
1646            let arg1 = 1;
1647            let arg2 = 1;
1648            assert_ne_or_internal_err!(arg1, arg2, "my cool context");
1649
1650            unreachable!("should return error");
1651        }
1652
1653        let res: Result<(), DataFusionError> = get_error();
1654        assert_error_have_message_and_backtrace(
1655            &res.unwrap_err(),
1656            "Internal error: Assertion failed: arg1 != arg2 (left: 1, right: 1): my cool context",
1657        );
1658    }
1659
1660    #[cfg(not(feature = "backtrace"))]
1661    #[test]
1662    fn test_disabled_backtrace_for_assert_ne_or_internal_err_without_args() {
1663        fn get_error() -> Result<(), DataFusionError> {
1664            let arg1 = 1;
1665            let arg2 = 1;
1666            assert_ne_or_internal_err!(arg1, arg2);
1667
1668            unreachable!("should return error");
1669        }
1670
1671        let res: Result<(), DataFusionError> = get_error();
1672        assert_internal_err_without_backtrace_and_equal(
1673            &res.unwrap_err(),
1674            "Internal error: Assertion failed: arg1 != arg2 (left: 1, right: 1)",
1675        );
1676    }
1677
1678    #[cfg(not(feature = "backtrace"))]
1679    #[test]
1680    fn test_disabled_backtrace_for_assert_ne_or_internal_err_with_args() {
1681        fn get_error() -> Result<(), DataFusionError> {
1682            let arg1 = 1;
1683            let arg2 = 1;
1684            assert_ne_or_internal_err!(arg1, arg2, "my cool context");
1685
1686            unreachable!("should return error");
1687        }
1688
1689        let res: Result<(), DataFusionError> = get_error();
1690        assert_internal_err_without_backtrace_and_equal(
1691            &res.unwrap_err(),
1692            "Internal error: Assertion failed: arg1 != arg2 (left: 1, right: 1): my cool context",
1693        );
1694    }
1695
1696    #[test]
1697    fn test_find_root_error() {
1698        do_root_test(
1699            DataFusionError::Context(
1700                "it happened!".to_string(),
1701                Box::new(DataFusionError::ResourcesExhausted("foo".to_string())),
1702            ),
1703            DataFusionError::ResourcesExhausted("foo".to_string()),
1704        );
1705
1706        do_root_test(
1707            DataFusionError::ArrowError(
1708                Box::new(ArrowError::ExternalError(Box::new(
1709                    DataFusionError::ResourcesExhausted("foo".to_string()),
1710                ))),
1711                None,
1712            ),
1713            DataFusionError::ResourcesExhausted("foo".to_string()),
1714        );
1715
1716        do_root_test(
1717            DataFusionError::External(Box::new(DataFusionError::ResourcesExhausted(
1718                "foo".to_string(),
1719            ))),
1720            DataFusionError::ResourcesExhausted("foo".to_string()),
1721        );
1722
1723        do_root_test(
1724            DataFusionError::External(Box::new(ArrowError::ExternalError(Box::new(
1725                DataFusionError::ResourcesExhausted("foo".to_string()),
1726            )))),
1727            DataFusionError::ResourcesExhausted("foo".to_string()),
1728        );
1729
1730        do_root_test(
1731            DataFusionError::ArrowError(
1732                Box::new(ArrowError::ExternalError(Box::new(
1733                    ArrowError::ExternalError(Box::new(
1734                        DataFusionError::ResourcesExhausted("foo".to_string()),
1735                    )),
1736                ))),
1737                None,
1738            ),
1739            DataFusionError::ResourcesExhausted("foo".to_string()),
1740        );
1741
1742        do_root_test(
1743            DataFusionError::External(Box::new(Arc::new(
1744                DataFusionError::ResourcesExhausted("foo".to_string()),
1745            ))),
1746            DataFusionError::ResourcesExhausted("foo".to_string()),
1747        );
1748
1749        do_root_test(
1750            DataFusionError::External(Box::new(Arc::new(ArrowError::ExternalError(
1751                Box::new(DataFusionError::ResourcesExhausted("foo".to_string())),
1752            )))),
1753            DataFusionError::ResourcesExhausted("foo".to_string()),
1754        );
1755    }
1756
1757    #[test]
1758    fn test_make_error_parse_input() {
1759        let res: Result<(), DataFusionError> = plan_err!("Err");
1760        let res = res.unwrap_err();
1761        assert_eq!(res.strip_backtrace(), "Error during planning: Err");
1762
1763        let extra1 = "extra1";
1764        let extra2 = "extra2";
1765
1766        let res: Result<(), DataFusionError> = plan_err!("Err {} {}", extra1, extra2);
1767        let res = res.unwrap_err();
1768        assert_eq!(
1769            res.strip_backtrace(),
1770            "Error during planning: Err extra1 extra2"
1771        );
1772
1773        let res: Result<(), DataFusionError> =
1774            plan_err!("Err {:?} {:#?}", extra1, extra2);
1775        let res = res.unwrap_err();
1776        assert_eq!(
1777            res.strip_backtrace(),
1778            "Error during planning: Err \"extra1\" \"extra2\""
1779        );
1780
1781        let res: Result<(), DataFusionError> = plan_err!("Err {extra1} {extra2}");
1782        let res = res.unwrap_err();
1783        assert_eq!(
1784            res.strip_backtrace(),
1785            "Error during planning: Err extra1 extra2"
1786        );
1787
1788        let res: Result<(), DataFusionError> = plan_err!("Err {extra1:?} {extra2:#?}");
1789        let res = res.unwrap_err();
1790        assert_eq!(
1791            res.strip_backtrace(),
1792            "Error during planning: Err \"extra1\" \"extra2\""
1793        );
1794    }
1795
1796    #[test]
1797    fn external_error() {
1798        // assert not wrapping DataFusionError
1799        let generic_error: GenericError =
1800            Box::new(DataFusionError::Plan("test".to_string()));
1801        let datafusion_error: DataFusionError = generic_error.into();
1802        println!("{}", datafusion_error.strip_backtrace());
1803        assert_eq!(
1804            datafusion_error.strip_backtrace(),
1805            "Error during planning: test"
1806        );
1807
1808        // assert wrapping other Error
1809        let generic_error: GenericError = Box::new(io::Error::other("io error"));
1810        let datafusion_error: DataFusionError = generic_error.into();
1811        println!("{}", datafusion_error.strip_backtrace());
1812        assert_eq!(
1813            datafusion_error.strip_backtrace(),
1814            "External error: io error"
1815        );
1816    }
1817
1818    #[test]
1819    fn external_error_no_recursive() {
1820        let generic_error_1: GenericError = Box::new(io::Error::other("io error"));
1821        let external_error_1: DataFusionError = generic_error_1.into();
1822        let generic_error_2: GenericError = Box::new(external_error_1);
1823        let external_error_2: DataFusionError = generic_error_2.into();
1824
1825        println!("{external_error_2}");
1826        assert!(
1827            external_error_2
1828                .to_string()
1829                .starts_with("External error: io error")
1830        );
1831    }
1832
1833    /// Model what happens when implementing SendableRecordBatchStream:
1834    /// DataFusion code needs to return an ArrowError
1835    fn return_arrow_error() -> arrow::error::Result<()> {
1836        // Expect the '?' to work
1837        Err(DataFusionError::Plan("foo".to_string()).into())
1838    }
1839
1840    /// Model what happens when using arrow kernels in DataFusion
1841    /// code: need to turn an ArrowError into a DataFusionError
1842    fn return_datafusion_error() -> Result<()> {
1843        // Expect the '?' to work
1844        Err(ArrowError::SchemaError("bar".to_string()).into())
1845    }
1846
1847    fn do_root_test(e: DataFusionError, exp: DataFusionError) {
1848        let e = e.find_root();
1849
1850        // DataFusionError does not implement Eq, so we use a string comparison + some cheap "same variant" test instead
1851        assert_eq!(e.strip_backtrace(), exp.strip_backtrace());
1852        assert_eq!(std::mem::discriminant(e), std::mem::discriminant(&exp),)
1853    }
1854
1855    #[test]
1856    fn test_iter() {
1857        let err = DataFusionError::Collection(vec![
1858            DataFusionError::Plan("a".to_string()),
1859            DataFusionError::Collection(vec![
1860                DataFusionError::Plan("b".to_string()),
1861                DataFusionError::Plan("c".to_string()),
1862            ]),
1863        ]);
1864        let errs = err.iter().collect::<Vec<_>>();
1865        assert_eq!(errs.len(), 3);
1866        assert_eq!(errs[0].strip_backtrace(), "Error during planning: a");
1867        assert_eq!(errs[1].strip_backtrace(), "Error during planning: b");
1868        assert_eq!(errs[2].strip_backtrace(), "Error during planning: c");
1869    }
1870}