Skip to main content

ursa_engine/
error.rs

1//! Error messages for people, not programmers.
2//!
3//! DataFusion's `Display` for an error prefixes it with the variant it came from
4//! ("Error during planning: ", "Arrow error: ", "External error: ") and, for a
5//! SQL syntax error, prints the parser error's `Debug` form
6//! (`ParserError("…")`). [`user_message`] walks the error instead and keeps only
7//! what happened. It reads the error's variants, not its text.
8//!
9//! Where DataFusion offers no typed error, the engine matches its text. Every
10//! such string is in [`matched`], with a test that makes DataFusion (or
11//! sqlparser) produce the message itself and checks the string is still in it,
12//! so an upgrade that rewords one fails there rather than quietly showing the
13//! user DataFusion's raw message.
14
15use datafusion::arrow::error::ArrowError;
16use datafusion::common::SchemaError;
17use datafusion::error::DataFusionError;
18use datafusion::sql::sqlparser::parser::ParserError;
19
20/// The DataFusion and sqlparser messages the engine and the CLI recognize by
21/// their text, because no typed error says the same (#265).
22///
23/// Each is matched as a substring or a prefix, as its doc says. The tests
24/// below trigger each message in DataFusion or sqlparser directly, not through
25/// Ursa's wrappers, and check the text is still there: when an upgrade changes
26/// the wording, they fail and name the string to update.
27pub mod matched {
28    /// The start of the context DataFusion's optimizer puts on a rule's error
29    /// (`Optimizer rule '…' failed`). Which rule failed is DataFusion's
30    /// business: [`super::user_message`] drops it and keeps the cause.
31    pub const OPTIMIZER_RULE_FAILED: &str = "Optimizer rule";
32
33    /// The start of sqlparser's tokenizer error for a string literal (or a
34    /// dollar-quoted or encoded one) still open at the end of the input. The
35    /// shell reads the next line instead of reporting it (`ursa-cli`'s
36    /// `input.rs`).
37    pub const TOKENIZER_UNTERMINATED: &str = "Unterminated";
38
39    /// In sqlparser's tokenizer error for a quoted identifier or a block
40    /// comment still open at the end of the input (`… before EOF.`,
41    /// `Unexpected EOF while in a multi-line comment`). The shell reads the
42    /// next line instead (`ursa-cli`'s `input.rs`).
43    pub const TOKENIZER_EOF: &str = "EOF";
44
45    /// In arrow's cast error for a date or timestamp outside the range of a
46    /// nanosecond timestamp (`Cannot cast Date32 value -100000000 to
47    /// Timestamp(ns): converted value exceeds the representable i64 range`),
48    /// which `date_trunc` and other timestamp functions meet on an
49    /// out-of-range date. Matched together with [`TIMESTAMP_NS`].
50    pub const TIMESTAMP_OVERFLOW: &str = "exceeds the representable i64 range";
51
52    /// The nanosecond timestamp type, as arrow names it in a cast error.
53    pub const TIMESTAMP_NS: &str = "Timestamp(ns)";
54
55    /// The start of the context DataFusion puts on an error inferring a CSV
56    /// file's schema, followed by the file's object store location, which
57    /// has lost its leading `/` (`Users/me/x.csv`): [`super::user_message`]
58    /// puts it back (#327, N14).
59    pub const CSV_FILE_CONTEXT: &str = "Error when processing CSV file ";
60}
61
62/// `location`, an object store location, as the local path the user wrote
63/// when it is one (`Users/me/x.csv` is `/Users/me/x.csv` if that exists).
64pub fn shown_path(location: &str) -> String {
65    #[cfg(all(unix, not(target_arch = "wasm32")))]
66    if !location.starts_with('/') && !location.contains("://") {
67        let absolute = format!("/{location}");
68        if std::path::Path::new(&absolute).exists() {
69            return absolute;
70        }
71    }
72    location.to_string()
73}
74
75/// What to do about a date outside a nanosecond timestamp's range (#328).
76const TIMESTAMP_RANGE_HINT: &str = "a timestamp in nanoseconds holds only dates from 1677-09-21 \
77     to 2262-04-11, and date_trunc and the other timestamp functions convert to one. Filter \
78     the dates first (WHERE d BETWEEN DATE '1678-01-01' AND DATE '2262-04-11'), or use \
79     extract(year FROM d) or date_part instead of date_trunc";
80
81/// The message to show a user for `err`: what went wrong, without the names of
82/// the internal error types it passed through.
83pub fn user_message(err: &DataFusionError) -> String {
84    let message = message_of(err);
85    if message.contains(matched::TIMESTAMP_OVERFLOW) && message.contains(matched::TIMESTAMP_NS) {
86        return format!("{message}; {TIMESTAMP_RANGE_HINT}");
87    }
88    message
89}
90
91fn message_of(err: &DataFusionError) -> String {
92    match err {
93        DataFusionError::ArrowError(e, _) => arrow_message(e),
94        // `Parquet error: …` says Parquet already; `EOF: …` and the rest do not.
95        DataFusionError::ParquetError(e) => match e.to_string() {
96            m if m.starts_with("Parquet error: ") => m,
97            m => format!("Parquet: {m}"),
98        },
99        DataFusionError::ObjectStore(e) => e.to_string(),
100        DataFusionError::IoError(e) => e.to_string(),
101        DataFusionError::SQL(e, _) => parser_message(e),
102        DataFusionError::NotImplemented(m)
103        | DataFusionError::Plan(m)
104        | DataFusionError::Configuration(m)
105        | DataFusionError::Execution(m)
106        | DataFusionError::ResourcesExhausted(m)
107        | DataFusionError::Substrait(m)
108        | DataFusionError::Ffi(m) => m.clone(),
109        DataFusionError::Internal(m) => format!("internal error: {m}"),
110        DataFusionError::SchemaError(e, _) => schema_message(e),
111        DataFusionError::ExecutionJoin(e) => e.to_string(),
112        DataFusionError::External(e) => external_message(e.as_ref()),
113        // Which optimizer rule hit the error is DataFusion's business.
114        DataFusionError::Context(context, inner)
115            if context.starts_with(matched::OPTIMIZER_RULE_FAILED) =>
116        {
117            message_of(inner)
118        }
119        DataFusionError::Context(context, inner) => {
120            match context.strip_prefix(matched::CSV_FILE_CONTEXT) {
121                Some(location) => format!(
122                    "cannot read '{}': {}",
123                    shown_path(location),
124                    message_of(inner)
125                ),
126                None => format!("{context}: {}", message_of(inner)),
127            }
128        }
129        DataFusionError::Diagnostic(_, inner) => message_of(inner),
130        DataFusionError::Collection(errs) => errs
131            .first()
132            .map(message_of)
133            .unwrap_or_else(|| "unknown error".to_string()),
134        DataFusionError::Shared(inner) => message_of(inner),
135    }
136}
137
138/// A schema error, with a hint for a name with a `-` in it: unquoted,
139/// `date-created` is `date - created`, so DataFusion reports `date` missing.
140fn schema_message(e: &SchemaError) -> String {
141    let message = e.to_string();
142    let SchemaError::FieldNotFound {
143        field,
144        valid_fields,
145    } = e
146    else {
147        return message;
148    };
149    // A valid name that the missing one is a `-`-separated part of.
150    let part_of =
151        |name: &str| name.split('-').count() > 1 && name.split('-').any(|p| p == field.name);
152    match valid_fields.iter().find(|c| part_of(&c.name)) {
153        Some(column) => {
154            let (first, rest) = message.split_once('\n').unwrap_or((&message, ""));
155            let mut out = format!(
156                "{first}\nA name that contains '-' must be quoted, or it is read as a \
157                 subtraction: write \"{}\"",
158                column.name.replace('"', "\"\"")
159            );
160            out.push_str(&format!(", not {}.", column.name));
161            if !rest.is_empty() {
162                out.push('\n');
163                out.push_str(rest);
164            }
165            out
166        }
167        None => message,
168    }
169}
170
171fn parser_message(e: &ParserError) -> String {
172    match e {
173        ParserError::TokenizerError(m) | ParserError::ParserError(m) => {
174            format!("syntax error: {m}")
175        }
176        ParserError::RecursionLimitExceeded => {
177            "syntax error: the statement is nested too deeply".to_string()
178        }
179    }
180}
181
182fn arrow_message(e: &ArrowError) -> String {
183    match e {
184        ArrowError::ExternalError(source) => external_message(source.as_ref()),
185        other => other.to_string(),
186    }
187}
188
189fn external_message(e: &(dyn std::error::Error + Send + Sync + 'static)) -> String {
190    if let Some(df) = e.downcast_ref::<DataFusionError>() {
191        message_of(df)
192    } else if let Some(arrow) = e.downcast_ref::<ArrowError>() {
193        arrow_message(arrow)
194    } else {
195        e.to_string()
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use std::sync::Arc;
202
203    use datafusion::common::tree_node::Transformed;
204    use datafusion::common::DFSchema;
205    use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
206    use datafusion::optimizer::{Optimizer, OptimizerConfig, OptimizerContext, OptimizerRule};
207    use datafusion::prelude::SessionContext;
208    use datafusion::sql::sqlparser::dialect::GenericDialect;
209    use datafusion::sql::sqlparser::tokenizer::Tokenizer;
210
211    use super::*;
212
213    /// An optimizer rule that always fails.
214    #[derive(Debug)]
215    struct Failing;
216
217    impl OptimizerRule for Failing {
218        fn name(&self) -> &str {
219            "failing"
220        }
221
222        fn supports_rewrite(&self) -> bool {
223            true
224        }
225
226        fn rewrite(
227            &self,
228            _plan: LogicalPlan,
229            _config: &dyn OptimizerConfig,
230        ) -> datafusion::error::Result<Transformed<LogicalPlan>> {
231            Err(DataFusionError::Plan("the cause".into()))
232        }
233    }
234
235    #[test]
236    fn datafusion_still_labels_a_failed_optimizer_rule() {
237        let optimizer = Optimizer::with_rules(vec![Arc::new(Failing)]);
238        let config = OptimizerContext::new().with_skip_failing_rules(false);
239        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
240            produce_one_row: false,
241            schema: Arc::new(DFSchema::empty()),
242        });
243        let err = optimizer
244            .optimize(plan, &config, |_, _| {})
245            .expect_err("the rule fails");
246        let DataFusionError::Context(label, _) = &err else {
247            panic!(
248                "DataFusion no longer wraps a failed optimizer rule's error in a context: {err:?}"
249            );
250        };
251        assert!(
252            label.starts_with(matched::OPTIMIZER_RULE_FAILED),
253            "DataFusion's label for a failed optimizer rule changed; update \
254             matched::OPTIMIZER_RULE_FAILED: {label}"
255        );
256        // And user_message keeps only the cause.
257        assert_eq!(user_message(&err), "the cause");
258    }
259
260    /// `user_message` reads a syntax error's variant, not DataFusion's
261    /// `ParserError("…")` text: DataFusion must still return the typed error.
262    #[tokio::test]
263    async fn datafusion_still_returns_syntax_errors_typed() {
264        let err = SessionContext::new()
265            .sql("SELEC 1")
266            .await
267            .expect_err("a syntax error");
268        assert!(
269            matches!(err.find_root(), DataFusionError::SQL(..)),
270            "DataFusion no longer returns a syntax error as DataFusionError::SQL: {err:?}"
271        );
272        let message = user_message(&err);
273        assert!(
274            message.starts_with("syntax error: ") && !message.contains("ParserError"),
275            "{message}"
276        );
277    }
278
279    /// sqlparser's tokenizer error for `sql`, which must fail.
280    fn tokenizer_error(sql: &str) -> String {
281        Tokenizer::new(&GenericDialect {}, sql)
282            .tokenize()
283            .expect_err("the tokenizer fails")
284            .message
285    }
286
287    #[test]
288    fn sqlparser_still_says_unterminated_and_eof() {
289        for sql in ["SELECT 'abc", "SELECT 'it''s"] {
290            let message = tokenizer_error(sql);
291            assert!(
292                message.starts_with(matched::TOKENIZER_UNTERMINATED),
293                "sqlparser's message for an open string changed; update \
294                 matched::TOKENIZER_UNTERMINATED: {sql}: {message}"
295            );
296        }
297        for sql in ["SELECT \"abc", "SELECT 1 /* a note"] {
298            let message = tokenizer_error(sql);
299            assert!(
300                message.contains(matched::TOKENIZER_EOF),
301                "sqlparser's message for an open quoted name or comment changed; update \
302                 matched::TOKENIZER_EOF: {sql}: {message}"
303            );
304        }
305    }
306
307    /// N14: a CSV file DataFusion cannot read is named by its path, with its
308    /// leading `/`, not by its object store location.
309    #[tokio::test]
310    async fn datafusion_still_names_a_bad_csv_file_by_its_location() {
311        let dir = tempfile::tempdir().unwrap();
312        let path = std::fs::canonicalize(dir.path()).unwrap().join("bad.csv");
313        std::fs::write(&path, "a,b\n1,2\n1,2,3\n").unwrap();
314        let ctx = SessionContext::new();
315        let err = ctx
316            .register_csv("t", path.to_str().unwrap(), Default::default())
317            .await
318            .unwrap_err();
319        let DataFusionError::Context(context, _) = &err else {
320            panic!("DataFusion no longer gives a bad CSV file context; update matched::CSV_FILE_CONTEXT: {err:?}");
321        };
322        assert!(
323            context.starts_with(matched::CSV_FILE_CONTEXT),
324            "DataFusion's context for a bad CSV file changed; update \
325             matched::CSV_FILE_CONTEXT: {context}"
326        );
327        let message = user_message(&err);
328        #[cfg(unix)]
329        assert!(
330            message.starts_with(&format!("cannot read '{}': ", path.display())),
331            "{message}"
332        );
333        #[cfg(not(unix))]
334        assert!(message.starts_with("cannot read "), "{message}");
335    }
336
337    #[test]
338    fn strips_variant_prefixes() {
339        let err = DataFusionError::Plan("table 'x' not found".into());
340        assert_eq!(user_message(&err), "table 'x' not found");
341        let err = DataFusionError::SQL(
342            Box::new(ParserError::ParserError("Expected: an expression".into())),
343            None,
344        );
345        assert_eq!(user_message(&err), "syntax error: Expected: an expression");
346        let err = DataFusionError::External(Box::new(DataFusionError::Execution("boom".into())));
347        assert_eq!(user_message(&err), "boom");
348    }
349
350    /// #328: an unquoted `date-created` is `date - created`; say to quote it.
351    #[tokio::test]
352    async fn a_hyphenated_name_says_to_quote_it() {
353        let ctx = SessionContext::new();
354        let sql = "SELECT date-created FROM (SELECT 1 AS \"date-created\", 2 AS x) t";
355        let err = ctx.sql(sql).await.unwrap_err();
356        assert_eq!(
357            user_message(&err),
358            "No field named date.\n\
359             A name that contains '-' must be quoted, or it is read as a subtraction: write \
360             \"date-created\", not date-created.\n\
361             Valid fields are t.\"date-created\", t.x."
362        );
363        // A missing name that is not part of one with a `-` gets no hint.
364        let sql = "SELECT nope FROM (SELECT 1 AS \"date-created\") t";
365        let err = ctx.sql(sql).await.unwrap_err();
366        assert!(
367            !user_message(&err).contains("quoted"),
368            "{}",
369            user_message(&err)
370        );
371    }
372
373    /// #328: a date out of a nanosecond timestamp's range, in date_trunc,
374    /// says what to do instead (and arrow still words the error as
375    /// [`matched::TIMESTAMP_OVERFLOW`] and [`matched::TIMESTAMP_NS`] say).
376    #[tokio::test]
377    async fn an_out_of_range_date_in_date_trunc_suggests_extract() {
378        let ctx = SessionContext::new();
379        let err = ctx
380            .sql("SELECT date_trunc('year', CAST(-100000000 AS DATE))")
381            .await
382            .unwrap()
383            .collect()
384            .await
385            .unwrap_err();
386        let raw = message_of(&err);
387        assert!(
388            raw.contains(matched::TIMESTAMP_OVERFLOW) && raw.contains(matched::TIMESTAMP_NS),
389            "arrow's message for an out-of-range timestamp cast changed; update \
390             matched::TIMESTAMP_OVERFLOW and TIMESTAMP_NS: {raw}"
391        );
392        let message = user_message(&err);
393        assert!(
394            message.ends_with(&format!("; {TIMESTAMP_RANGE_HINT}")),
395            "{message}"
396        );
397        assert!(message.contains("extract(year FROM d)"), "{message}");
398    }
399}