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    /// The start of DataFusion's error for a call of a scalar or aggregate
62    /// function it does not have (`Invalid function 'pagerank'.`), followed
63    /// by the name. `ursa-sql` says a graph function is a table function.
64    pub const INVALID_FUNCTION: &str = "Invalid function '";
65
66    /// The start and end of DataFusion's error for a table it cannot find
67    /// (`table 'datafusion.edges.csv' not found`). `ursa-sql` says to quote
68    /// an unquoted file name.
69    pub const TABLE_NOT_FOUND_START: &str = "table '";
70    /// See [`TABLE_NOT_FOUND_START`].
71    pub const TABLE_NOT_FOUND_END: &str = "' not found";
72
73    /// In DataFusion's error for `SET` of a name with no namespace it knows
74    /// (`could not find config namespace for key "threads"`). `ursa-sql`
75    /// names the prefixes Ursa's settings have.
76    pub const UNKNOWN_SETTING: &str = "could not find config namespace for key";
77}
78
79/// `location`, an object store location, as the local path the user wrote
80/// when it is one (`Users/me/x.csv` is `/Users/me/x.csv` if that exists).
81pub fn shown_path(location: &str) -> String {
82    #[cfg(all(unix, not(target_arch = "wasm32")))]
83    if !location.starts_with('/') && !location.contains("://") {
84        let absolute = format!("/{location}");
85        if std::path::Path::new(&absolute).exists() {
86            return absolute;
87        }
88    }
89    location.to_string()
90}
91
92/// What to do about a date outside a nanosecond timestamp's range (#328).
93const TIMESTAMP_RANGE_HINT: &str = "a timestamp in nanoseconds holds only dates from 1677-09-21 \
94     to 2262-04-11, and date_trunc and the other timestamp functions convert to one. Filter \
95     the dates first (WHERE d BETWEEN DATE '1678-01-01' AND DATE '2262-04-11'), or use \
96     extract(year FROM d) or date_part instead of date_trunc";
97
98/// The message to show a user for `err`: what went wrong, without the names of
99/// the internal error types it passed through.
100pub fn user_message(err: &DataFusionError) -> String {
101    let message = message_of(err);
102    if message.contains(matched::TIMESTAMP_OVERFLOW) && message.contains(matched::TIMESTAMP_NS) {
103        return format!("{message}; {TIMESTAMP_RANGE_HINT}");
104    }
105    message
106}
107
108fn message_of(err: &DataFusionError) -> String {
109    match err {
110        DataFusionError::ArrowError(e, _) => arrow_message(e),
111        // `Parquet error: …` says Parquet already; `EOF: …` and the rest do not.
112        DataFusionError::ParquetError(e) => match e.to_string() {
113            m if m.starts_with("Parquet error: ") => m,
114            m => format!("Parquet: {m}"),
115        },
116        DataFusionError::ObjectStore(e) => e.to_string(),
117        DataFusionError::IoError(e) => e.to_string(),
118        DataFusionError::SQL(e, _) => parser_message(e),
119        DataFusionError::NotImplemented(m)
120        | DataFusionError::Plan(m)
121        | DataFusionError::Configuration(m)
122        | DataFusionError::Execution(m)
123        | DataFusionError::ResourcesExhausted(m)
124        | DataFusionError::Substrait(m)
125        | DataFusionError::Ffi(m) => m.clone(),
126        DataFusionError::Internal(m) => format!("internal error: {m}"),
127        DataFusionError::SchemaError(e, _) => schema_message(e),
128        DataFusionError::ExecutionJoin(e) => e.to_string(),
129        DataFusionError::External(e) => external_message(e.as_ref()),
130        // Which optimizer rule hit the error is DataFusion's business.
131        DataFusionError::Context(context, inner)
132            if context.starts_with(matched::OPTIMIZER_RULE_FAILED) =>
133        {
134            message_of(inner)
135        }
136        DataFusionError::Context(context, inner) => {
137            match context.strip_prefix(matched::CSV_FILE_CONTEXT) {
138                Some(location) => format!(
139                    "cannot read '{}': {}",
140                    shown_path(location),
141                    message_of(inner)
142                ),
143                None => format!("{context}: {}", message_of(inner)),
144            }
145        }
146        DataFusionError::Diagnostic(_, inner) => message_of(inner),
147        DataFusionError::Collection(errs) => errs
148            .first()
149            .map(message_of)
150            .unwrap_or_else(|| "unknown error".to_string()),
151        DataFusionError::Shared(inner) => message_of(inner),
152    }
153}
154
155/// A schema error, with a hint for a name with a `-` in it: unquoted,
156/// `date-created` is `date - created`, so DataFusion reports `date` missing.
157fn schema_message(e: &SchemaError) -> String {
158    let message = e.to_string();
159    let SchemaError::FieldNotFound {
160        field,
161        valid_fields,
162    } = e
163    else {
164        return message;
165    };
166    // A valid name that the missing one is a `-`-separated part of.
167    let part_of =
168        |name: &str| name.split('-').count() > 1 && name.split('-').any(|p| p == field.name);
169    match valid_fields.iter().find(|c| part_of(&c.name)) {
170        Some(column) => {
171            let (first, rest) = message.split_once('\n').unwrap_or((&message, ""));
172            let mut out = format!(
173                "{first}\nA name that contains '-' must be quoted, or it is read as a \
174                 subtraction: write \"{}\"",
175                column.name.replace('"', "\"\"")
176            );
177            out.push_str(&format!(", not {}.", column.name));
178            if !rest.is_empty() {
179                out.push('\n');
180                out.push_str(rest);
181            }
182            out
183        }
184        None => message,
185    }
186}
187
188fn parser_message(e: &ParserError) -> String {
189    match e {
190        ParserError::TokenizerError(m) | ParserError::ParserError(m) => {
191            format!("syntax error: {m}")
192        }
193        ParserError::RecursionLimitExceeded => {
194            "syntax error: the statement is nested too deeply".to_string()
195        }
196    }
197}
198
199fn arrow_message(e: &ArrowError) -> String {
200    match e {
201        ArrowError::ExternalError(source) => external_message(source.as_ref()),
202        other => other.to_string(),
203    }
204}
205
206fn external_message(e: &(dyn std::error::Error + Send + Sync + 'static)) -> String {
207    if let Some(df) = e.downcast_ref::<DataFusionError>() {
208        message_of(df)
209    } else if let Some(arrow) = e.downcast_ref::<ArrowError>() {
210        arrow_message(arrow)
211    } else {
212        e.to_string()
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use std::sync::Arc;
219
220    use datafusion::common::tree_node::Transformed;
221    use datafusion::common::DFSchema;
222    use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
223    use datafusion::optimizer::{Optimizer, OptimizerConfig, OptimizerContext, OptimizerRule};
224    use datafusion::prelude::SessionContext;
225    use datafusion::sql::sqlparser::dialect::GenericDialect;
226    use datafusion::sql::sqlparser::tokenizer::Tokenizer;
227
228    use super::*;
229
230    /// An optimizer rule that always fails.
231    #[derive(Debug)]
232    struct Failing;
233
234    impl OptimizerRule for Failing {
235        fn name(&self) -> &str {
236            "failing"
237        }
238
239        fn supports_rewrite(&self) -> bool {
240            true
241        }
242
243        fn rewrite(
244            &self,
245            _plan: LogicalPlan,
246            _config: &dyn OptimizerConfig,
247        ) -> datafusion::error::Result<Transformed<LogicalPlan>> {
248            Err(DataFusionError::Plan("the cause".into()))
249        }
250    }
251
252    #[test]
253    fn datafusion_still_labels_a_failed_optimizer_rule() {
254        let optimizer = Optimizer::with_rules(vec![Arc::new(Failing)]);
255        let config = OptimizerContext::new().with_skip_failing_rules(false);
256        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
257            produce_one_row: false,
258            schema: Arc::new(DFSchema::empty()),
259        });
260        let err = optimizer
261            .optimize(plan, &config, |_, _| {})
262            .expect_err("the rule fails");
263        let DataFusionError::Context(label, _) = &err else {
264            panic!(
265                "DataFusion no longer wraps a failed optimizer rule's error in a context: {err:?}"
266            );
267        };
268        assert!(
269            label.starts_with(matched::OPTIMIZER_RULE_FAILED),
270            "DataFusion's label for a failed optimizer rule changed; update \
271             matched::OPTIMIZER_RULE_FAILED: {label}"
272        );
273        // And user_message keeps only the cause.
274        assert_eq!(user_message(&err), "the cause");
275    }
276
277    /// `user_message` reads a syntax error's variant, not DataFusion's
278    /// `ParserError("…")` text: DataFusion must still return the typed error.
279    #[tokio::test]
280    async fn datafusion_still_returns_syntax_errors_typed() {
281        let err = SessionContext::new()
282            .sql("SELEC 1")
283            .await
284            .expect_err("a syntax error");
285        assert!(
286            matches!(err.find_root(), DataFusionError::SQL(..)),
287            "DataFusion no longer returns a syntax error as DataFusionError::SQL: {err:?}"
288        );
289        let message = user_message(&err);
290        assert!(
291            message.starts_with("syntax error: ") && !message.contains("ParserError"),
292            "{message}"
293        );
294    }
295
296    /// sqlparser's tokenizer error for `sql`, which must fail.
297    fn tokenizer_error(sql: &str) -> String {
298        Tokenizer::new(&GenericDialect {}, sql)
299            .tokenize()
300            .expect_err("the tokenizer fails")
301            .message
302    }
303
304    #[test]
305    fn sqlparser_still_says_unterminated_and_eof() {
306        for sql in ["SELECT 'abc", "SELECT 'it''s"] {
307            let message = tokenizer_error(sql);
308            assert!(
309                message.starts_with(matched::TOKENIZER_UNTERMINATED),
310                "sqlparser's message for an open string changed; update \
311                 matched::TOKENIZER_UNTERMINATED: {sql}: {message}"
312            );
313        }
314        for sql in ["SELECT \"abc", "SELECT 1 /* a note"] {
315            let message = tokenizer_error(sql);
316            assert!(
317                message.contains(matched::TOKENIZER_EOF),
318                "sqlparser's message for an open quoted name or comment changed; update \
319                 matched::TOKENIZER_EOF: {sql}: {message}"
320            );
321        }
322    }
323
324    /// #417: the messages `ursa-sql` adds a DuckDB hint to.
325    #[tokio::test]
326    async fn datafusion_still_says_invalid_function_table_not_found_and_no_namespace() {
327        let ctx = SessionContext::new();
328        let message = |sql: &'static str| {
329            let ctx = ctx.clone();
330            async move { user_message(&ctx.sql(sql).await.unwrap_err()) }
331        };
332        let m = message("SELECT pagerank(1)").await;
333        assert!(
334            m.starts_with(&format!("{}pagerank'", matched::INVALID_FUNCTION)),
335            "update matched::INVALID_FUNCTION: {m}"
336        );
337        let m = message("SELECT * FROM edges.csv").await;
338        assert!(
339            m.starts_with(matched::TABLE_NOT_FOUND_START)
340                && m.ends_with(matched::TABLE_NOT_FOUND_END),
341            "update matched::TABLE_NOT_FOUND_*: {m}"
342        );
343        let m = message("SET threads = 2").await;
344        assert!(
345            m.contains(matched::UNKNOWN_SETTING),
346            "update matched::UNKNOWN_SETTING: {m}"
347        );
348    }
349
350    /// N14: a CSV file DataFusion cannot read is named by its path, with its
351    /// leading `/`, not by its object store location.
352    #[tokio::test]
353    async fn datafusion_still_names_a_bad_csv_file_by_its_location() {
354        let dir = tempfile::tempdir().unwrap();
355        let path = std::fs::canonicalize(dir.path()).unwrap().join("bad.csv");
356        std::fs::write(&path, "a,b\n1,2\n1,2,3\n").unwrap();
357        let ctx = SessionContext::new();
358        let err = ctx
359            .register_csv("t", path.to_str().unwrap(), Default::default())
360            .await
361            .unwrap_err();
362        let DataFusionError::Context(context, _) = &err else {
363            panic!("DataFusion no longer gives a bad CSV file context; update matched::CSV_FILE_CONTEXT: {err:?}");
364        };
365        assert!(
366            context.starts_with(matched::CSV_FILE_CONTEXT),
367            "DataFusion's context for a bad CSV file changed; update \
368             matched::CSV_FILE_CONTEXT: {context}"
369        );
370        let message = user_message(&err);
371        #[cfg(unix)]
372        assert!(
373            message.starts_with(&format!("cannot read '{}': ", path.display())),
374            "{message}"
375        );
376        #[cfg(not(unix))]
377        assert!(message.starts_with("cannot read "), "{message}");
378    }
379
380    #[test]
381    fn strips_variant_prefixes() {
382        let err = DataFusionError::Plan("table 'x' not found".into());
383        assert_eq!(user_message(&err), "table 'x' not found");
384        let err = DataFusionError::SQL(
385            Box::new(ParserError::ParserError("Expected: an expression".into())),
386            None,
387        );
388        assert_eq!(user_message(&err), "syntax error: Expected: an expression");
389        let err = DataFusionError::External(Box::new(DataFusionError::Execution("boom".into())));
390        assert_eq!(user_message(&err), "boom");
391    }
392
393    /// #328: an unquoted `date-created` is `date - created`; say to quote it.
394    #[tokio::test]
395    async fn a_hyphenated_name_says_to_quote_it() {
396        let ctx = SessionContext::new();
397        let sql = "SELECT date-created FROM (SELECT 1 AS \"date-created\", 2 AS x) t";
398        let err = ctx.sql(sql).await.unwrap_err();
399        assert_eq!(
400            user_message(&err),
401            "No field named date.\n\
402             A name that contains '-' must be quoted, or it is read as a subtraction: write \
403             \"date-created\", not date-created.\n\
404             Valid fields are t.\"date-created\", t.x."
405        );
406        // A missing name that is not part of one with a `-` gets no hint.
407        let sql = "SELECT nope FROM (SELECT 1 AS \"date-created\") t";
408        let err = ctx.sql(sql).await.unwrap_err();
409        assert!(
410            !user_message(&err).contains("quoted"),
411            "{}",
412            user_message(&err)
413        );
414    }
415
416    /// #328: a date out of a nanosecond timestamp's range, in date_trunc,
417    /// says what to do instead (and arrow still words the error as
418    /// [`matched::TIMESTAMP_OVERFLOW`] and [`matched::TIMESTAMP_NS`] say).
419    #[tokio::test]
420    async fn an_out_of_range_date_in_date_trunc_suggests_extract() {
421        let ctx = SessionContext::new();
422        let err = ctx
423            .sql("SELECT date_trunc('year', CAST(-100000000 AS DATE))")
424            .await
425            .unwrap()
426            .collect()
427            .await
428            .unwrap_err();
429        let raw = message_of(&err);
430        assert!(
431            raw.contains(matched::TIMESTAMP_OVERFLOW) && raw.contains(matched::TIMESTAMP_NS),
432            "arrow's message for an out-of-range timestamp cast changed; update \
433             matched::TIMESTAMP_OVERFLOW and TIMESTAMP_NS: {raw}"
434        );
435        let message = user_message(&err);
436        assert!(
437            message.ends_with(&format!("; {TIMESTAMP_RANGE_HINT}")),
438            "{message}"
439        );
440        assert!(message.contains("extract(year FROM d)"), "{message}");
441    }
442}