Skip to main content

rudb_common/
error.rs

1//! The error model.
2//!
3//! `spec/04-architecture.md` section 4.9 says errors are values, `Result` is everywhere, and no
4//! path reachable from user input panics. It also says every error carries a code, a message and
5//! optionally a span into the query text, that the codes are stable because clients switch on
6//! them, and that the messages match DuckDB's where a DuckDB message is what a test asserts on.
7//!
8//! This module is where all three of those obligations live.
9
10use std::fmt;
11
12/// The result type used everywhere in the workspace.
13pub type Result<T> = std::result::Result<T, Error>;
14
15/// A byte range into the query text.
16///
17/// Half open, so `start` is the first byte and `end` is one past the last, which is what slicing
18/// wants and what every editor protocol in existence expects. Byte offsets rather than character
19/// offsets because that is what the parser has and converting is the caller's problem, once, at
20/// the point where a human is going to read it.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct Span {
23    /// First byte of the span.
24    pub start: u32,
25    /// One past the last byte of the span.
26    pub end: u32,
27}
28
29impl Span {
30    /// A span over `start .. end`.
31    #[must_use]
32    pub const fn new(start: u32, end: u32) -> Self {
33        Self { start, end }
34    }
35
36    /// The number of bytes covered, which is zero for a span that points between two characters.
37    #[must_use]
38    pub const fn len(self) -> u32 {
39        self.end.saturating_sub(self.start)
40    }
41
42    /// Whether the span covers no bytes.
43    #[must_use]
44    pub const fn is_empty(self) -> bool {
45        self.len() == 0
46    }
47}
48
49/// What kind of thing went wrong.
50///
51/// These are stable and they are part of the public interface, because a client that retries on
52/// one class of failure and gives up on another has to be able to tell them apart without reading
53/// the message. Adding a variant is a compatible change and renaming one is not.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55#[non_exhaustive]
56pub enum ErrorCode {
57    /// The text is not SQL.
58    Parser,
59    /// The text is SQL and a value in it is not one the statement can take.
60    ///
61    /// DuckDB's own line between this and [`ErrorCode::Parser`] is not one anybody would draw
62    /// twice, and it is on the wire, so it is here: `SET threads=0` is a syntax error there and a
63    /// syntax error here.
64    Syntax,
65    /// The text is SQL and it does not mean anything, for example a column that is not in scope.
66    Binder,
67    /// A named object is missing, or one that should be missing is not.
68    Catalog,
69    /// A value will not convert to the type it is being asked for.
70    Conversion,
71    /// A value is outside what its type can hold.
72    OutOfRange,
73    /// An argument is wrong in a way that is not a type error, for example a negative length.
74    InvalidInput,
75    /// An allocation failed or a memory limit was reached. An error, never an abort.
76    OutOfMemory,
77    /// The filesystem, the network or the object store said no.
78    Io,
79    /// It is in the plan and it is not built yet.
80    NotImplemented,
81    /// A primary key, unique, not null or check constraint was violated.
82    Constraint,
83    /// An entry cannot go because others depend on it, for example a schema that still holds
84    /// tables.
85    Dependency,
86    /// A sequence was asked for a value it cannot give, for example one past its maximum.
87    Sequence,
88    /// A conflict, an abort, or a statement issued outside a transaction that needs one.
89    Transaction,
90    /// A setting cannot be applied in the current engine configuration.
91    Settings,
92    /// The query was cancelled. Cooperative, checked at morsel boundaries.
93    Interrupt,
94    /// A value is one the function refuses outright rather than one of the wrong type, for example
95    /// an empty list handed to `list_reduce` with nothing to start from.
96    ParameterNotAllowed,
97    /// Two types were asked to meet and cannot, for example two structs of different sizes.
98    MismatchType,
99    /// A type cannot be used where it was put, for example a list as the key of an index.
100    InvalidType,
101    /// An invariant this code is responsible for does not hold. Always a bug here, never in the
102    /// query.
103    Internal,
104}
105
106impl ErrorCode {
107    /// The prefix DuckDB puts on a message with this code.
108    ///
109    /// Compatibility obligation from `spec/12-duckdb-compat.md` section 12.5: a great many tests
110    /// in the wild assert on the exact text of an error, so the prefix is DuckDB's spelling
111    /// including the parts that look like typos. `Not implemented Error` really is capitalised
112    /// that way upstream, and `INTERNAL Error` really is shouted.
113    #[must_use]
114    pub const fn duckdb_name(self) -> &'static str {
115        match self {
116            Self::Parser => "Parser Error",
117            Self::Syntax => "Syntax Error",
118            Self::Binder => "Binder Error",
119            Self::Catalog => "Catalog Error",
120            Self::Conversion => "Conversion Error",
121            Self::OutOfRange => "Out of Range Error",
122            Self::InvalidInput => "Invalid Input Error",
123            Self::OutOfMemory => "Out of Memory Error",
124            Self::Io => "IO Error",
125            Self::NotImplemented => "Not implemented Error",
126            Self::Constraint => "Constraint Error",
127            Self::Dependency => "Dependency Error",
128            Self::Sequence => "Sequence Error",
129            Self::Transaction => "TransactionContext Error",
130            Self::Settings => "Settings Error",
131            Self::Interrupt => "Interrupt Error",
132            Self::ParameterNotAllowed => "Parameter Not Allowed Error",
133            Self::MismatchType => "Mismatch Type Error",
134            Self::InvalidType => "Invalid type Error",
135            Self::Internal => "INTERNAL Error",
136        }
137    }
138
139    /// Whether an error with this code says something about the query rather than about us.
140    ///
141    /// Used by the fuzzing harness in `spec/16-testing.md` section 16.4, which treats a rejected
142    /// query as a normal outcome and an internal error as a finding.
143    #[must_use]
144    pub const fn is_user_error(self) -> bool {
145        matches!(
146            self,
147            Self::Parser
148                | Self::Syntax
149                | Self::Binder
150                | Self::Catalog
151                | Self::Conversion
152                | Self::OutOfRange
153                | Self::InvalidInput
154                | Self::Constraint
155                | Self::Dependency
156                | Self::Sequence
157                | Self::Transaction
158                | Self::Settings
159                | Self::ParameterNotAllowed
160                | Self::MismatchType
161                | Self::InvalidType
162        )
163    }
164}
165
166impl fmt::Display for ErrorCode {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.write_str(self.duckdb_name())
169    }
170}
171
172/// An error, carrying a code, a message and optionally where in the query it happened.
173///
174/// The payload is boxed so that `Error` is one pointer wide, which keeps `Result<T>` the same size
175/// as `T` for every `T` that has a niche. Errors are rare and results are returned from every
176/// function in the workspace, so the cost belongs on the rare path.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct Error(Box<Payload>);
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181struct Payload {
182    code: ErrorCode,
183    message: String,
184    span: Option<Span>,
185    message_only: bool,
186}
187
188impl Error {
189    /// An error with a code and a message and no span.
190    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
191        Self(Box::new(Payload { code, message: message.into(), span: None, message_only: false }))
192    }
193
194    /// The same error, with the part of the query it is about.
195    #[must_use]
196    pub fn with_span(mut self, span: Span) -> Self {
197        self.0.span = Some(span);
198        self
199    }
200
201    /// Attaches the range only when a more specific caller has not already attached one.
202    #[must_use]
203    pub fn with_fallback_span(mut self, span: Span) -> Self {
204        if self.0.span.is_none() && !span.is_empty() {
205            self.0.span = Some(span);
206        }
207        self
208    }
209
210    /// What kind of thing went wrong.
211    #[must_use]
212    pub fn code(&self) -> ErrorCode {
213        self.0.code
214    }
215
216    /// The message, without the code prefix that `Display` adds.
217    #[must_use]
218    pub fn message(&self) -> &str {
219        &self.0.message
220    }
221
222    /// Where in the query text this is about, if it is about a place.
223    #[must_use]
224    pub fn span(&self) -> Option<Span> {
225        self.0.span
226    }
227
228    /// Renders this error as the structured JSON form DuckDB returns for `errors_as_json`.
229    #[must_use]
230    pub fn into_json(mut self) -> Self {
231        let exception_type = self.0.code.json_name();
232        let subtype = self.0.code.json_subtype(&self.0.message);
233        let mut fields = vec![
234            ("exception_type", exception_type.to_string()),
235            ("exception_message", self.0.message.clone()),
236        ];
237        if let Some(span) = self.0.span {
238            fields.push(("location", format!("[{},{}]", span.start, span.len())));
239            fields.push(("position", span.start.to_string()));
240        }
241        if let Some(subtype) = subtype {
242            fields.push(("error_subtype", subtype.to_string()));
243        }
244        self.0.message = json_object(&fields);
245        self.0.message_only = true;
246        self
247    }
248
249    /// The text is not SQL.
250    pub fn parser(message: impl Into<String>) -> Self {
251        Self::new(ErrorCode::Parser, message)
252    }
253
254    /// The text is SQL and a value in it is not one the statement can take.
255    pub fn syntax(message: impl Into<String>) -> Self {
256        Self::new(ErrorCode::Syntax, message)
257    }
258
259    /// The text is SQL and it does not mean anything.
260    pub fn binder(message: impl Into<String>) -> Self {
261        Self::new(ErrorCode::Binder, message)
262    }
263
264    /// A named object is missing, or one that should be missing is not.
265    pub fn catalog(message: impl Into<String>) -> Self {
266        Self::new(ErrorCode::Catalog, message)
267    }
268
269    /// A value will not convert to the type it is being asked for.
270    pub fn conversion(message: impl Into<String>) -> Self {
271        Self::new(ErrorCode::Conversion, message)
272    }
273
274    /// A value is outside what its type can hold.
275    pub fn out_of_range(message: impl Into<String>) -> Self {
276        Self::new(ErrorCode::OutOfRange, message)
277    }
278
279    /// An argument is wrong in a way that is not a type error.
280    pub fn invalid_input(message: impl Into<String>) -> Self {
281        Self::new(ErrorCode::InvalidInput, message)
282    }
283
284    /// An allocation failed or a memory limit was reached.
285    pub fn out_of_memory(message: impl Into<String>) -> Self {
286        Self::new(ErrorCode::OutOfMemory, message)
287    }
288
289    /// The filesystem, the network or the object store said no.
290    pub fn io(message: impl Into<String>) -> Self {
291        Self::new(ErrorCode::Io, message)
292    }
293
294    /// It is in the plan and it is not built yet.
295    pub fn not_implemented(message: impl Into<String>) -> Self {
296        Self::new(ErrorCode::NotImplemented, message)
297    }
298
299    /// A constraint was violated.
300    pub fn constraint(message: impl Into<String>) -> Self {
301        Self::new(ErrorCode::Constraint, message)
302    }
303
304    /// A conflict, an abort, or a statement issued outside a transaction that needs one.
305    pub fn transaction(message: impl Into<String>) -> Self {
306        Self::new(ErrorCode::Transaction, message)
307    }
308
309    /// A setting cannot be applied in the current engine configuration.
310    pub fn settings(message: impl Into<String>) -> Self {
311        Self::new(ErrorCode::Settings, message)
312    }
313
314    /// A value the function refuses outright.
315    pub fn parameter_not_allowed(message: impl Into<String>) -> Self {
316        Self::new(ErrorCode::ParameterNotAllowed, message)
317    }
318
319    /// An entry that others depend on.
320    pub fn dependency(message: impl Into<String>) -> Self {
321        Self::new(ErrorCode::Dependency, message)
322    }
323
324    /// A sequence that cannot give what was asked of it.
325    pub fn sequence(message: impl Into<String>) -> Self {
326        Self::new(ErrorCode::Sequence, message)
327    }
328
329    /// Two types that cannot meet.
330    pub fn mismatch_type(message: impl Into<String>) -> Self {
331        Self::new(ErrorCode::MismatchType, message)
332    }
333
334    /// A type used where it cannot be.
335    pub fn invalid_type(message: impl Into<String>) -> Self {
336        Self::new(ErrorCode::InvalidType, message)
337    }
338
339    /// The query was cancelled.
340    pub fn interrupt(message: impl Into<String>) -> Self {
341        Self::new(ErrorCode::Interrupt, message)
342    }
343
344    /// An invariant this code is responsible for does not hold.
345    ///
346    /// Reaching this is always a bug in the database and never a bug in the query, which is why it
347    /// reads differently from the others and why the fuzzer treats it as a finding.
348    pub fn internal(message: impl Into<String>) -> Self {
349        Self::new(ErrorCode::Internal, message)
350    }
351}
352
353impl fmt::Display for Error {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        if self.0.message_only {
356            return f.write_str(&self.0.message);
357        }
358        write!(f, "{}: {}", self.0.code, self.0.message)
359    }
360}
361
362impl ErrorCode {
363    const fn json_name(self) -> &'static str {
364        match self {
365            Self::Parser => "Parser",
366            Self::Syntax => "Syntax",
367            Self::Binder => "Binder",
368            Self::Catalog => "Catalog",
369            Self::Conversion => "Conversion",
370            Self::OutOfRange => "Out of Range",
371            Self::InvalidInput => "Invalid Input",
372            Self::OutOfMemory => "Out of Memory",
373            Self::Io => "IO",
374            Self::NotImplemented => "Not implemented",
375            Self::Constraint => "Constraint",
376            Self::Dependency => "Dependency",
377            Self::Sequence => "Sequence",
378            Self::Transaction => "TransactionContext",
379            Self::Settings => "Settings",
380            Self::Interrupt => "Interrupt",
381            Self::ParameterNotAllowed => "Parameter Not Allowed",
382            Self::MismatchType => "Mismatch Type",
383            Self::InvalidType => "Invalid type",
384            Self::Internal => "INTERNAL",
385        }
386    }
387
388    fn json_subtype(self, message: &str) -> Option<&'static str> {
389        match self {
390            Self::Parser => Some("SYNTAX_ERROR"),
391            Self::Binder if message.starts_with("Referenced column") => Some("COLUMN_NOT_FOUND"),
392            Self::Binder if message.contains("No function matches") => Some("NO_MATCHING_FUNCTION"),
393            Self::Catalog if message.contains("does not exist") => Some("MISSING_ENTRY"),
394            _ => None,
395        }
396    }
397}
398
399fn json_object(fields: &[(&str, String)]) -> String {
400    let mut out = String::from("{");
401    for (index, (name, value)) in fields.iter().enumerate() {
402        if index != 0 {
403            out.push(',');
404        }
405        out.push('"');
406        out.push_str(name);
407        out.push_str("\":\"");
408        for character in value.chars() {
409            match character {
410                '"' => out.push_str("\\\""),
411                '\\' => out.push_str("\\\\"),
412                '\n' => out.push_str("\\n"),
413                '\r' => out.push_str("\\r"),
414                '\t' => out.push_str("\\t"),
415                character if character <= '\u{1f}' => {
416                    use std::fmt::Write as _;
417                    let _ = write!(out, "\\u{:04x}", character as u32);
418                }
419                character => out.push(character),
420            }
421        }
422        out.push('"');
423    }
424    out.push('}');
425    out
426}
427
428impl std::error::Error for Error {}
429
430impl From<std::io::Error> for Error {
431    fn from(error: std::io::Error) -> Self {
432        Self::io(error.to_string())
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::{Error, ErrorCode, Span};
439
440    #[test]
441    fn an_error_prints_the_way_duckdb_prints_it() {
442        let error = Error::binder("Referenced column \"nope\" not found in FROM clause!");
443        assert_eq!(
444            error.to_string(),
445            "Binder Error: Referenced column \"nope\" not found in FROM clause!"
446        );
447    }
448
449    #[test]
450    fn a_json_error_is_structured_and_has_no_text_prefix() {
451        let error = Error::binder("Referenced column \"nope\" not found\nnext")
452            .with_span(Span::new(7, 11))
453            .into_json();
454        assert_eq!(
455            error.to_string(),
456            "{\"exception_type\":\"Binder\",\"exception_message\":\"Referenced column \\\"nope\\\" not found\\nnext\",\"location\":\"[7,4]\",\"position\":\"7\",\"error_subtype\":\"COLUMN_NOT_FOUND\"}"
457        );
458        assert_eq!(error.code(), ErrorCode::Binder);
459    }
460
461    #[test]
462    fn a_result_is_no_wider_than_the_value_in_it() {
463        // The reason the payload is boxed. If this ever fails, every function in the workspace
464        // got more expensive to return from and nobody noticed.
465        assert_eq!(size_of::<Error>(), size_of::<usize>());
466        assert_eq!(size_of::<Result<String, Error>>(), size_of::<String>());
467    }
468
469    #[test]
470    fn a_span_survives_being_attached() {
471        let error = Error::parser("syntax error at or near \"FROM\"").with_span(Span::new(7, 11));
472        assert_eq!(error.span(), Some(Span::new(7, 11)));
473        assert_eq!(error.span().map(Span::len), Some(4));
474        assert_eq!(error.code(), ErrorCode::Parser);
475    }
476
477    #[test]
478    fn a_fallback_span_keeps_the_more_specific_range() {
479        let specific = Error::binder("missing")
480            .with_span(Span::new(7, 14))
481            .with_fallback_span(Span::new(0, 20));
482        assert_eq!(specific.span(), Some(Span::new(7, 14)));
483        let fallback = Error::binder("missing").with_fallback_span(Span::new(0, 20));
484        assert_eq!(fallback.span(), Some(Span::new(0, 20)));
485        assert_eq!(Error::binder("missing").with_fallback_span(Span::new(0, 0)).span(), None);
486    }
487
488    #[test]
489    fn the_fuzzer_can_tell_our_bugs_from_the_query_s_bugs() {
490        assert!(ErrorCode::Binder.is_user_error());
491        assert!(ErrorCode::Conversion.is_user_error());
492        assert!(!ErrorCode::Internal.is_user_error());
493        assert!(!ErrorCode::OutOfMemory.is_user_error());
494        // Not implemented is ours rather than the query's, because the query was legitimate and we
495        // are the reason it did not run.
496        assert!(!ErrorCode::NotImplemented.is_user_error());
497    }
498}