1#[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
45pub type Result<T, E = DataFusionError> = result::Result<T, E>;
47
48pub type SharedResult<T> = result::Result<T, Arc<DataFusionError>>;
50
51pub type GenericError = Box<dyn Error + Send + Sync>;
53
54#[derive(Debug)]
56pub enum DataFusionError {
57 ArrowError(Box<ArrowError>, Option<String>),
61 #[cfg(feature = "parquet")]
63 ParquetError(Box<ParquetError>),
64 #[cfg(feature = "object_store")]
66 ObjectStore(Box<object_store::Error>),
67 IoError(io::Error),
69 #[cfg(feature = "sql")]
73 SQL(Box<ParserError>, Option<String>),
74 NotImplemented(String),
80 Internal(String),
97 Plan(String),
103 Configuration(String),
105 SchemaError(Box<SchemaError>, Box<Option<String>>),
113 Execution(String),
120 ExecutionJoin(Box<JoinError>),
124 ResourcesExhausted(String),
129 External(GenericError),
133 Context(String, Box<DataFusionError>),
135 Substrait(String),
138 Diagnostic(Box<Diagnostic>, Box<DataFusionError>),
143 Collection(Vec<DataFusionError>),
150 Shared(Arc<DataFusionError>),
156 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#[derive(Debug)]
171pub enum SchemaError {
172 AmbiguousReference { field: Box<Column> },
174 DuplicateQualifiedField {
176 qualifier: Box<TableReference>,
177 name: String,
178 },
179 DuplicateUnqualifiedField { name: String },
181 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
213fn closest_valid_field<'a>(
216 field: &Column,
217 valid_fields: &'a [Column],
218) -> Option<&'a Column> {
219 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 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
260const 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 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 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 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 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 pub const BACK_TRACE_SEP: &'static str = "\n\nbacktrace: ";
489
490 pub fn find_root(&self) -> &Self {
506 let mut last_datafusion_error = self;
510 let mut root_error: &dyn Error = self;
511 while let Some(source) = root_error.source() {
512 root_error = source;
514 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 last_datafusion_error = e.as_ref();
521 }
522 }
523 last_datafusion_error
525 }
526
527 pub fn context(self, description: impl Into<String>) -> Self {
529 Self::Context(description.into(), Box::new(self))
530 }
531
532 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 #[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 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 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 pub fn with_diagnostic(self, diagnostic: Diagnostic) -> Self {
662 Self::Diagnostic(Box::new(diagnostic), Box::new(self))
663 }
664
665 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 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 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#[derive(Debug, Default)]
766pub struct DataFusionErrorBuilder(Vec<DataFusionError>);
767
768impl DataFusionErrorBuilder {
769 pub fn new() -> Self {
771 Default::default()
772 }
773
774 pub fn add_error(&mut self, error: DataFusionError) {
787 self.0.push(error);
788 }
789
790 pub fn with_error(mut self, error: DataFusionError) -> Self {
803 self.0.push(error);
804 self
805 }
806
807 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#[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#[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#[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#[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
944macro_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_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_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
1002make_error!(
1004 plan_err,
1005 _plan_err,
1006 plan_datafusion_err,
1007 _plan_datafusion_err,
1008 Plan
1009);
1010
1011make_error!(
1013 internal_err,
1014 _internal_err,
1015 internal_datafusion_err,
1016 _internal_datafusion_err,
1017 Internal
1018);
1019
1020make_error!(
1022 not_impl_err,
1023 _not_impl_err,
1024 not_impl_datafusion_err,
1025 _not_impl_datafusion_err,
1026 NotImplemented
1027);
1028
1029make_error!(
1031 exec_err,
1032 _exec_err,
1033 exec_datafusion_err,
1034 _exec_datafusion_err,
1035 Execution
1036);
1037
1038make_error!(
1040 config_err,
1041 _config_err,
1042 config_datafusion_err,
1043 _config_datafusion_err,
1044 Configuration
1045);
1046
1047make_error!(
1049 substrait_err,
1050 _substrait_err,
1051 substrait_datafusion_err,
1052 _substrait_datafusion_err,
1053 Substrait
1054);
1055
1056make_error!(
1058 resources_err,
1059 _resources_err,
1060 resources_datafusion_err,
1061 _resources_datafusion_err,
1062 ResourcesExhausted
1063);
1064
1065make_error!(
1067 ffi_err,
1068 _ffi_err,
1069 ffi_datafusion_err,
1070 _ffi_datafusion_err,
1071 Ffi
1072);
1073
1074#[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#[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#[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#[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#[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#[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
1154pub use schema_err as _schema_err;
1157
1158pub 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
1170pub 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 #[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 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 #[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 #[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 #[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 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 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 fn return_arrow_error() -> arrow::error::Result<()> {
1836 Err(DataFusionError::Plan("foo".to_string()).into())
1838 }
1839
1840 fn return_datafusion_error() -> Result<()> {
1843 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 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}