ursa-engine 0.12.0

Ursa's SQL engine session: a DataFusion session that reads files by path, locally or in object storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Error messages for people, not programmers.
//!
//! DataFusion's `Display` for an error prefixes it with the variant it came from
//! ("Error during planning: ", "Arrow error: ", "External error: ") and, for a
//! SQL syntax error, prints the parser error's `Debug` form
//! (`ParserError("…")`). [`user_message`] walks the error instead and keeps only
//! what happened. It reads the error's variants, not its text.
//!
//! Where DataFusion offers no typed error, the engine matches its text. Every
//! such string is in [`matched`], with a test that makes DataFusion (or
//! sqlparser) produce the message itself and checks the string is still in it,
//! so an upgrade that rewords one fails there rather than quietly showing the
//! user DataFusion's raw message.

use datafusion::arrow::error::ArrowError;
use datafusion::common::SchemaError;
use datafusion::error::DataFusionError;
use datafusion::sql::sqlparser::parser::ParserError;

/// The DataFusion and sqlparser messages the engine and the CLI recognize by
/// their text, because no typed error says the same (#265).
///
/// Each is matched as a substring or a prefix, as its doc says. The tests
/// below trigger each message in DataFusion or sqlparser directly, not through
/// Ursa's wrappers, and check the text is still there: when an upgrade changes
/// the wording, they fail and name the string to update.
pub mod matched {
    /// The start of the context DataFusion's optimizer puts on a rule's error
    /// (`Optimizer rule '…' failed`). Which rule failed is DataFusion's
    /// business: [`super::user_message`] drops it and keeps the cause.
    pub const OPTIMIZER_RULE_FAILED: &str = "Optimizer rule";

    /// The start of sqlparser's tokenizer error for a string literal (or a
    /// dollar-quoted or encoded one) still open at the end of the input. The
    /// shell reads the next line instead of reporting it (`ursa-cli`'s
    /// `input.rs`).
    pub const TOKENIZER_UNTERMINATED: &str = "Unterminated";

    /// In sqlparser's tokenizer error for a quoted identifier or a block
    /// comment still open at the end of the input (`… before EOF.`,
    /// `Unexpected EOF while in a multi-line comment`). The shell reads the
    /// next line instead (`ursa-cli`'s `input.rs`).
    pub const TOKENIZER_EOF: &str = "EOF";

    /// In arrow's cast error for a date or timestamp outside the range of a
    /// nanosecond timestamp (`Cannot cast Date32 value -100000000 to
    /// Timestamp(ns): converted value exceeds the representable i64 range`),
    /// which `date_trunc` and other timestamp functions meet on an
    /// out-of-range date. Matched together with [`TIMESTAMP_NS`].
    pub const TIMESTAMP_OVERFLOW: &str = "exceeds the representable i64 range";

    /// The nanosecond timestamp type, as arrow names it in a cast error.
    pub const TIMESTAMP_NS: &str = "Timestamp(ns)";

    /// The start of the context DataFusion puts on an error inferring a CSV
    /// file's schema, followed by the file's object store location, which
    /// has lost its leading `/` (`Users/me/x.csv`): [`super::user_message`]
    /// puts it back (#327, N14).
    pub const CSV_FILE_CONTEXT: &str = "Error when processing CSV file ";

    /// The start of DataFusion's error for a call of a scalar or aggregate
    /// function it does not have (`Invalid function 'pagerank'.`), followed
    /// by the name. `ursa-sql` says a graph function is a table function.
    pub const INVALID_FUNCTION: &str = "Invalid function '";

    /// The start and end of DataFusion's error for a table it cannot find
    /// (`table 'datafusion.edges.csv' not found`). `ursa-sql` says to quote
    /// an unquoted file name.
    pub const TABLE_NOT_FOUND_START: &str = "table '";
    /// See [`TABLE_NOT_FOUND_START`].
    pub const TABLE_NOT_FOUND_END: &str = "' not found";

    /// In DataFusion's error for `SET` of a name with no namespace it knows
    /// (`could not find config namespace for key "threads"`). `ursa-sql`
    /// names the prefixes Ursa's settings have.
    pub const UNKNOWN_SETTING: &str = "could not find config namespace for key";
}

/// `location`, an object store location, as the local path the user wrote
/// when it is one (`Users/me/x.csv` is `/Users/me/x.csv` if that exists).
pub fn shown_path(location: &str) -> String {
    #[cfg(all(unix, not(target_arch = "wasm32")))]
    if !location.starts_with('/') && !location.contains("://") {
        let absolute = format!("/{location}");
        if std::path::Path::new(&absolute).exists() {
            return absolute;
        }
    }
    location.to_string()
}

/// What to do about a date outside a nanosecond timestamp's range (#328).
const TIMESTAMP_RANGE_HINT: &str = "a timestamp in nanoseconds holds only dates from 1677-09-21 \
     to 2262-04-11, and date_trunc and the other timestamp functions convert to one. Filter \
     the dates first (WHERE d BETWEEN DATE '1678-01-01' AND DATE '2262-04-11'), or use \
     extract(year FROM d) or date_part instead of date_trunc";

/// The message to show a user for `err`: what went wrong, without the names of
/// the internal error types it passed through.
pub fn user_message(err: &DataFusionError) -> String {
    let message = message_of(err);
    if message.contains(matched::TIMESTAMP_OVERFLOW) && message.contains(matched::TIMESTAMP_NS) {
        return format!("{message}; {TIMESTAMP_RANGE_HINT}");
    }
    message
}

fn message_of(err: &DataFusionError) -> String {
    match err {
        DataFusionError::ArrowError(e, _) => arrow_message(e),
        // `Parquet error: …` says Parquet already; `EOF: …` and the rest do not.
        DataFusionError::ParquetError(e) => match e.to_string() {
            m if m.starts_with("Parquet error: ") => m,
            m => format!("Parquet: {m}"),
        },
        DataFusionError::ObjectStore(e) => e.to_string(),
        DataFusionError::IoError(e) => e.to_string(),
        DataFusionError::SQL(e, _) => parser_message(e),
        DataFusionError::NotImplemented(m)
        | DataFusionError::Plan(m)
        | DataFusionError::Configuration(m)
        | DataFusionError::Execution(m)
        | DataFusionError::ResourcesExhausted(m)
        | DataFusionError::Substrait(m)
        | DataFusionError::Ffi(m) => m.clone(),
        DataFusionError::Internal(m) => format!("internal error: {m}"),
        DataFusionError::SchemaError(e, _) => schema_message(e),
        DataFusionError::ExecutionJoin(e) => e.to_string(),
        DataFusionError::External(e) => external_message(e.as_ref()),
        // Which optimizer rule hit the error is DataFusion's business.
        DataFusionError::Context(context, inner)
            if context.starts_with(matched::OPTIMIZER_RULE_FAILED) =>
        {
            message_of(inner)
        }
        DataFusionError::Context(context, inner) => {
            match context.strip_prefix(matched::CSV_FILE_CONTEXT) {
                Some(location) => format!(
                    "cannot read '{}': {}",
                    shown_path(location),
                    message_of(inner)
                ),
                None => format!("{context}: {}", message_of(inner)),
            }
        }
        DataFusionError::Diagnostic(_, inner) => message_of(inner),
        DataFusionError::Collection(errs) => errs
            .first()
            .map(message_of)
            .unwrap_or_else(|| "unknown error".to_string()),
        DataFusionError::Shared(inner) => message_of(inner),
    }
}

/// A schema error, with a hint for a name with a `-` in it: unquoted,
/// `date-created` is `date - created`, so DataFusion reports `date` missing.
fn schema_message(e: &SchemaError) -> String {
    let message = e.to_string();
    let SchemaError::FieldNotFound {
        field,
        valid_fields,
    } = e
    else {
        return message;
    };
    // A valid name that the missing one is a `-`-separated part of.
    let part_of =
        |name: &str| name.split('-').count() > 1 && name.split('-').any(|p| p == field.name);
    match valid_fields.iter().find(|c| part_of(&c.name)) {
        Some(column) => {
            let (first, rest) = message.split_once('\n').unwrap_or((&message, ""));
            let mut out = format!(
                "{first}\nA name that contains '-' must be quoted, or it is read as a \
                 subtraction: write \"{}\"",
                column.name.replace('"', "\"\"")
            );
            out.push_str(&format!(", not {}.", column.name));
            if !rest.is_empty() {
                out.push('\n');
                out.push_str(rest);
            }
            out
        }
        None => message,
    }
}

fn parser_message(e: &ParserError) -> String {
    match e {
        ParserError::TokenizerError(m) | ParserError::ParserError(m) => {
            format!("syntax error: {m}")
        }
        ParserError::RecursionLimitExceeded => {
            "syntax error: the statement is nested too deeply".to_string()
        }
    }
}

fn arrow_message(e: &ArrowError) -> String {
    match e {
        ArrowError::ExternalError(source) => external_message(source.as_ref()),
        other => other.to_string(),
    }
}

fn external_message(e: &(dyn std::error::Error + Send + Sync + 'static)) -> String {
    if let Some(df) = e.downcast_ref::<DataFusionError>() {
        message_of(df)
    } else if let Some(arrow) = e.downcast_ref::<ArrowError>() {
        arrow_message(arrow)
    } else {
        e.to_string()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use datafusion::common::tree_node::Transformed;
    use datafusion::common::DFSchema;
    use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
    use datafusion::optimizer::{Optimizer, OptimizerConfig, OptimizerContext, OptimizerRule};
    use datafusion::prelude::SessionContext;
    use datafusion::sql::sqlparser::dialect::GenericDialect;
    use datafusion::sql::sqlparser::tokenizer::Tokenizer;

    use super::*;

    /// An optimizer rule that always fails.
    #[derive(Debug)]
    struct Failing;

    impl OptimizerRule for Failing {
        fn name(&self) -> &str {
            "failing"
        }

        fn supports_rewrite(&self) -> bool {
            true
        }

        fn rewrite(
            &self,
            _plan: LogicalPlan,
            _config: &dyn OptimizerConfig,
        ) -> datafusion::error::Result<Transformed<LogicalPlan>> {
            Err(DataFusionError::Plan("the cause".into()))
        }
    }

    #[test]
    fn datafusion_still_labels_a_failed_optimizer_rule() {
        let optimizer = Optimizer::with_rules(vec![Arc::new(Failing)]);
        let config = OptimizerContext::new().with_skip_failing_rules(false);
        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
            produce_one_row: false,
            schema: Arc::new(DFSchema::empty()),
        });
        let err = optimizer
            .optimize(plan, &config, |_, _| {})
            .expect_err("the rule fails");
        let DataFusionError::Context(label, _) = &err else {
            panic!(
                "DataFusion no longer wraps a failed optimizer rule's error in a context: {err:?}"
            );
        };
        assert!(
            label.starts_with(matched::OPTIMIZER_RULE_FAILED),
            "DataFusion's label for a failed optimizer rule changed; update \
             matched::OPTIMIZER_RULE_FAILED: {label}"
        );
        // And user_message keeps only the cause.
        assert_eq!(user_message(&err), "the cause");
    }

    /// `user_message` reads a syntax error's variant, not DataFusion's
    /// `ParserError("…")` text: DataFusion must still return the typed error.
    #[tokio::test]
    async fn datafusion_still_returns_syntax_errors_typed() {
        let err = SessionContext::new()
            .sql("SELEC 1")
            .await
            .expect_err("a syntax error");
        assert!(
            matches!(err.find_root(), DataFusionError::SQL(..)),
            "DataFusion no longer returns a syntax error as DataFusionError::SQL: {err:?}"
        );
        let message = user_message(&err);
        assert!(
            message.starts_with("syntax error: ") && !message.contains("ParserError"),
            "{message}"
        );
    }

    /// sqlparser's tokenizer error for `sql`, which must fail.
    fn tokenizer_error(sql: &str) -> String {
        Tokenizer::new(&GenericDialect {}, sql)
            .tokenize()
            .expect_err("the tokenizer fails")
            .message
    }

    #[test]
    fn sqlparser_still_says_unterminated_and_eof() {
        for sql in ["SELECT 'abc", "SELECT 'it''s"] {
            let message = tokenizer_error(sql);
            assert!(
                message.starts_with(matched::TOKENIZER_UNTERMINATED),
                "sqlparser's message for an open string changed; update \
                 matched::TOKENIZER_UNTERMINATED: {sql}: {message}"
            );
        }
        for sql in ["SELECT \"abc", "SELECT 1 /* a note"] {
            let message = tokenizer_error(sql);
            assert!(
                message.contains(matched::TOKENIZER_EOF),
                "sqlparser's message for an open quoted name or comment changed; update \
                 matched::TOKENIZER_EOF: {sql}: {message}"
            );
        }
    }

    /// #417: the messages `ursa-sql` adds a DuckDB hint to.
    #[tokio::test]
    async fn datafusion_still_says_invalid_function_table_not_found_and_no_namespace() {
        let ctx = SessionContext::new();
        let message = |sql: &'static str| {
            let ctx = ctx.clone();
            async move { user_message(&ctx.sql(sql).await.unwrap_err()) }
        };
        let m = message("SELECT pagerank(1)").await;
        assert!(
            m.starts_with(&format!("{}pagerank'", matched::INVALID_FUNCTION)),
            "update matched::INVALID_FUNCTION: {m}"
        );
        let m = message("SELECT * FROM edges.csv").await;
        assert!(
            m.starts_with(matched::TABLE_NOT_FOUND_START)
                && m.ends_with(matched::TABLE_NOT_FOUND_END),
            "update matched::TABLE_NOT_FOUND_*: {m}"
        );
        let m = message("SET threads = 2").await;
        assert!(
            m.contains(matched::UNKNOWN_SETTING),
            "update matched::UNKNOWN_SETTING: {m}"
        );
    }

    /// N14: a CSV file DataFusion cannot read is named by its path, with its
    /// leading `/`, not by its object store location.
    #[tokio::test]
    async fn datafusion_still_names_a_bad_csv_file_by_its_location() {
        let dir = tempfile::tempdir().unwrap();
        let path = std::fs::canonicalize(dir.path()).unwrap().join("bad.csv");
        std::fs::write(&path, "a,b\n1,2\n1,2,3\n").unwrap();
        let ctx = SessionContext::new();
        let err = ctx
            .register_csv("t", path.to_str().unwrap(), Default::default())
            .await
            .unwrap_err();
        let DataFusionError::Context(context, _) = &err else {
            panic!("DataFusion no longer gives a bad CSV file context; update matched::CSV_FILE_CONTEXT: {err:?}");
        };
        assert!(
            context.starts_with(matched::CSV_FILE_CONTEXT),
            "DataFusion's context for a bad CSV file changed; update \
             matched::CSV_FILE_CONTEXT: {context}"
        );
        let message = user_message(&err);
        #[cfg(unix)]
        assert!(
            message.starts_with(&format!("cannot read '{}': ", path.display())),
            "{message}"
        );
        #[cfg(not(unix))]
        assert!(message.starts_with("cannot read "), "{message}");
    }

    #[test]
    fn strips_variant_prefixes() {
        let err = DataFusionError::Plan("table 'x' not found".into());
        assert_eq!(user_message(&err), "table 'x' not found");
        let err = DataFusionError::SQL(
            Box::new(ParserError::ParserError("Expected: an expression".into())),
            None,
        );
        assert_eq!(user_message(&err), "syntax error: Expected: an expression");
        let err = DataFusionError::External(Box::new(DataFusionError::Execution("boom".into())));
        assert_eq!(user_message(&err), "boom");
    }

    /// #328: an unquoted `date-created` is `date - created`; say to quote it.
    #[tokio::test]
    async fn a_hyphenated_name_says_to_quote_it() {
        let ctx = SessionContext::new();
        let sql = "SELECT date-created FROM (SELECT 1 AS \"date-created\", 2 AS x) t";
        let err = ctx.sql(sql).await.unwrap_err();
        assert_eq!(
            user_message(&err),
            "No field named date.\n\
             A name that contains '-' must be quoted, or it is read as a subtraction: write \
             \"date-created\", not date-created.\n\
             Valid fields are t.\"date-created\", t.x."
        );
        // A missing name that is not part of one with a `-` gets no hint.
        let sql = "SELECT nope FROM (SELECT 1 AS \"date-created\") t";
        let err = ctx.sql(sql).await.unwrap_err();
        assert!(
            !user_message(&err).contains("quoted"),
            "{}",
            user_message(&err)
        );
    }

    /// #328: a date out of a nanosecond timestamp's range, in date_trunc,
    /// says what to do instead (and arrow still words the error as
    /// [`matched::TIMESTAMP_OVERFLOW`] and [`matched::TIMESTAMP_NS`] say).
    #[tokio::test]
    async fn an_out_of_range_date_in_date_trunc_suggests_extract() {
        let ctx = SessionContext::new();
        let err = ctx
            .sql("SELECT date_trunc('year', CAST(-100000000 AS DATE))")
            .await
            .unwrap()
            .collect()
            .await
            .unwrap_err();
        let raw = message_of(&err);
        assert!(
            raw.contains(matched::TIMESTAMP_OVERFLOW) && raw.contains(matched::TIMESTAMP_NS),
            "arrow's message for an out-of-range timestamp cast changed; update \
             matched::TIMESTAMP_OVERFLOW and TIMESTAMP_NS: {raw}"
        );
        let message = user_message(&err);
        assert!(
            message.ends_with(&format!("; {TIMESTAMP_RANGE_HINT}")),
            "{message}"
        );
        assert!(message.contains("extract(year FROM d)"), "{message}");
    }
}