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    /// An invariant this code is responsible for does not hold. Always a bug here, never in the
100    /// query.
101    Internal,
102}
103
104impl ErrorCode {
105    /// The prefix DuckDB puts on a message with this code.
106    ///
107    /// Compatibility obligation from `spec/12-duckdb-compat.md` section 12.5: a great many tests
108    /// in the wild assert on the exact text of an error, so the prefix is DuckDB's spelling
109    /// including the parts that look like typos. `Not implemented Error` really is capitalised
110    /// that way upstream, and `INTERNAL Error` really is shouted.
111    #[must_use]
112    pub const fn duckdb_name(self) -> &'static str {
113        match self {
114            Self::Parser => "Parser Error",
115            Self::Syntax => "Syntax Error",
116            Self::Binder => "Binder Error",
117            Self::Catalog => "Catalog Error",
118            Self::Conversion => "Conversion Error",
119            Self::OutOfRange => "Out of Range Error",
120            Self::InvalidInput => "Invalid Input Error",
121            Self::OutOfMemory => "Out of Memory Error",
122            Self::Io => "IO Error",
123            Self::NotImplemented => "Not implemented Error",
124            Self::Constraint => "Constraint Error",
125            Self::Dependency => "Dependency Error",
126            Self::Sequence => "Sequence Error",
127            Self::Transaction => "TransactionContext Error",
128            Self::Settings => "Settings Error",
129            Self::Interrupt => "Interrupt Error",
130            Self::ParameterNotAllowed => "Parameter Not Allowed Error",
131            Self::MismatchType => "Mismatch Type Error",
132            Self::Internal => "INTERNAL Error",
133        }
134    }
135
136    /// Whether an error with this code says something about the query rather than about us.
137    ///
138    /// Used by the fuzzing harness in `spec/16-testing.md` section 16.4, which treats a rejected
139    /// query as a normal outcome and an internal error as a finding.
140    #[must_use]
141    pub const fn is_user_error(self) -> bool {
142        matches!(
143            self,
144            Self::Parser
145                | Self::Syntax
146                | Self::Binder
147                | Self::Catalog
148                | Self::Conversion
149                | Self::OutOfRange
150                | Self::InvalidInput
151                | Self::Constraint
152                | Self::Dependency
153                | Self::Sequence
154                | Self::Transaction
155                | Self::Settings
156                | Self::ParameterNotAllowed
157                | Self::MismatchType
158        )
159    }
160}
161
162impl fmt::Display for ErrorCode {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.write_str(self.duckdb_name())
165    }
166}
167
168/// An error, carrying a code, a message and optionally where in the query it happened.
169///
170/// The payload is boxed so that `Error` is one pointer wide, which keeps `Result<T>` the same size
171/// as `T` for every `T` that has a niche. Errors are rare and results are returned from every
172/// function in the workspace, so the cost belongs on the rare path.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub struct Error(Box<Payload>);
175
176#[derive(Debug, Clone, PartialEq, Eq)]
177struct Payload {
178    code: ErrorCode,
179    message: String,
180    span: Option<Span>,
181    message_only: bool,
182}
183
184impl Error {
185    /// An error with a code and a message and no span.
186    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
187        Self(Box::new(Payload { code, message: message.into(), span: None, message_only: false }))
188    }
189
190    /// The same error, with the part of the query it is about.
191    #[must_use]
192    pub fn with_span(mut self, span: Span) -> Self {
193        self.0.span = Some(span);
194        self
195    }
196
197    /// Attaches the range only when a more specific caller has not already attached one.
198    #[must_use]
199    pub fn with_fallback_span(mut self, span: Span) -> Self {
200        if self.0.span.is_none() && !span.is_empty() {
201            self.0.span = Some(span);
202        }
203        self
204    }
205
206    /// What kind of thing went wrong.
207    #[must_use]
208    pub fn code(&self) -> ErrorCode {
209        self.0.code
210    }
211
212    /// The message, without the code prefix that `Display` adds.
213    #[must_use]
214    pub fn message(&self) -> &str {
215        &self.0.message
216    }
217
218    /// Where in the query text this is about, if it is about a place.
219    #[must_use]
220    pub fn span(&self) -> Option<Span> {
221        self.0.span
222    }
223
224    /// Renders this error as the structured JSON form DuckDB returns for `errors_as_json`.
225    #[must_use]
226    pub fn into_json(mut self) -> Self {
227        let exception_type = self.0.code.json_name();
228        let subtype = self.0.code.json_subtype(&self.0.message);
229        let mut fields = vec![
230            ("exception_type", exception_type.to_string()),
231            ("exception_message", self.0.message.clone()),
232        ];
233        if let Some(span) = self.0.span {
234            fields.push(("location", format!("[{},{}]", span.start, span.len())));
235            fields.push(("position", span.start.to_string()));
236        }
237        if let Some(subtype) = subtype {
238            fields.push(("error_subtype", subtype.to_string()));
239        }
240        self.0.message = json_object(&fields);
241        self.0.message_only = true;
242        self
243    }
244
245    /// The text is not SQL.
246    pub fn parser(message: impl Into<String>) -> Self {
247        Self::new(ErrorCode::Parser, message)
248    }
249
250    /// The text is SQL and a value in it is not one the statement can take.
251    pub fn syntax(message: impl Into<String>) -> Self {
252        Self::new(ErrorCode::Syntax, message)
253    }
254
255    /// The text is SQL and it does not mean anything.
256    pub fn binder(message: impl Into<String>) -> Self {
257        Self::new(ErrorCode::Binder, message)
258    }
259
260    /// A named object is missing, or one that should be missing is not.
261    pub fn catalog(message: impl Into<String>) -> Self {
262        Self::new(ErrorCode::Catalog, message)
263    }
264
265    /// A value will not convert to the type it is being asked for.
266    pub fn conversion(message: impl Into<String>) -> Self {
267        Self::new(ErrorCode::Conversion, message)
268    }
269
270    /// A value is outside what its type can hold.
271    pub fn out_of_range(message: impl Into<String>) -> Self {
272        Self::new(ErrorCode::OutOfRange, message)
273    }
274
275    /// An argument is wrong in a way that is not a type error.
276    pub fn invalid_input(message: impl Into<String>) -> Self {
277        Self::new(ErrorCode::InvalidInput, message)
278    }
279
280    /// An allocation failed or a memory limit was reached.
281    pub fn out_of_memory(message: impl Into<String>) -> Self {
282        Self::new(ErrorCode::OutOfMemory, message)
283    }
284
285    /// The filesystem, the network or the object store said no.
286    pub fn io(message: impl Into<String>) -> Self {
287        Self::new(ErrorCode::Io, message)
288    }
289
290    /// It is in the plan and it is not built yet.
291    pub fn not_implemented(message: impl Into<String>) -> Self {
292        Self::new(ErrorCode::NotImplemented, message)
293    }
294
295    /// A constraint was violated.
296    pub fn constraint(message: impl Into<String>) -> Self {
297        Self::new(ErrorCode::Constraint, message)
298    }
299
300    /// A conflict, an abort, or a statement issued outside a transaction that needs one.
301    pub fn transaction(message: impl Into<String>) -> Self {
302        Self::new(ErrorCode::Transaction, message)
303    }
304
305    /// A setting cannot be applied in the current engine configuration.
306    pub fn settings(message: impl Into<String>) -> Self {
307        Self::new(ErrorCode::Settings, message)
308    }
309
310    /// A value the function refuses outright.
311    pub fn parameter_not_allowed(message: impl Into<String>) -> Self {
312        Self::new(ErrorCode::ParameterNotAllowed, message)
313    }
314
315    /// An entry that others depend on.
316    pub fn dependency(message: impl Into<String>) -> Self {
317        Self::new(ErrorCode::Dependency, message)
318    }
319
320    /// A sequence that cannot give what was asked of it.
321    pub fn sequence(message: impl Into<String>) -> Self {
322        Self::new(ErrorCode::Sequence, message)
323    }
324
325    /// Two types that cannot meet.
326    pub fn mismatch_type(message: impl Into<String>) -> Self {
327        Self::new(ErrorCode::MismatchType, message)
328    }
329
330    /// The query was cancelled.
331    pub fn interrupt(message: impl Into<String>) -> Self {
332        Self::new(ErrorCode::Interrupt, message)
333    }
334
335    /// An invariant this code is responsible for does not hold.
336    ///
337    /// Reaching this is always a bug in the database and never a bug in the query, which is why it
338    /// reads differently from the others and why the fuzzer treats it as a finding.
339    pub fn internal(message: impl Into<String>) -> Self {
340        Self::new(ErrorCode::Internal, message)
341    }
342}
343
344impl fmt::Display for Error {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        if self.0.message_only {
347            return f.write_str(&self.0.message);
348        }
349        write!(f, "{}: {}", self.0.code, self.0.message)
350    }
351}
352
353impl ErrorCode {
354    const fn json_name(self) -> &'static str {
355        match self {
356            Self::Parser => "Parser",
357            Self::Syntax => "Syntax",
358            Self::Binder => "Binder",
359            Self::Catalog => "Catalog",
360            Self::Conversion => "Conversion",
361            Self::OutOfRange => "Out of Range",
362            Self::InvalidInput => "Invalid Input",
363            Self::OutOfMemory => "Out of Memory",
364            Self::Io => "IO",
365            Self::NotImplemented => "Not implemented",
366            Self::Constraint => "Constraint",
367            Self::Dependency => "Dependency",
368            Self::Sequence => "Sequence",
369            Self::Transaction => "TransactionContext",
370            Self::Settings => "Settings",
371            Self::Interrupt => "Interrupt",
372            Self::ParameterNotAllowed => "Parameter Not Allowed",
373            Self::MismatchType => "Mismatch Type",
374            Self::Internal => "INTERNAL",
375        }
376    }
377
378    fn json_subtype(self, message: &str) -> Option<&'static str> {
379        match self {
380            Self::Parser => Some("SYNTAX_ERROR"),
381            Self::Binder if message.starts_with("Referenced column") => Some("COLUMN_NOT_FOUND"),
382            Self::Binder if message.contains("No function matches") => Some("NO_MATCHING_FUNCTION"),
383            Self::Catalog if message.contains("does not exist") => Some("MISSING_ENTRY"),
384            _ => None,
385        }
386    }
387}
388
389fn json_object(fields: &[(&str, String)]) -> String {
390    let mut out = String::from("{");
391    for (index, (name, value)) in fields.iter().enumerate() {
392        if index != 0 {
393            out.push(',');
394        }
395        out.push('"');
396        out.push_str(name);
397        out.push_str("\":\"");
398        for character in value.chars() {
399            match character {
400                '"' => out.push_str("\\\""),
401                '\\' => out.push_str("\\\\"),
402                '\n' => out.push_str("\\n"),
403                '\r' => out.push_str("\\r"),
404                '\t' => out.push_str("\\t"),
405                character if character <= '\u{1f}' => {
406                    use std::fmt::Write as _;
407                    let _ = write!(out, "\\u{:04x}", character as u32);
408                }
409                character => out.push(character),
410            }
411        }
412        out.push('"');
413    }
414    out.push('}');
415    out
416}
417
418impl std::error::Error for Error {}
419
420impl From<std::io::Error> for Error {
421    fn from(error: std::io::Error) -> Self {
422        Self::io(error.to_string())
423    }
424}
425
426#[cfg(test)]
427mod tests {
428    use super::{Error, ErrorCode, Span};
429
430    #[test]
431    fn an_error_prints_the_way_duckdb_prints_it() {
432        let error = Error::binder("Referenced column \"nope\" not found in FROM clause!");
433        assert_eq!(
434            error.to_string(),
435            "Binder Error: Referenced column \"nope\" not found in FROM clause!"
436        );
437    }
438
439    #[test]
440    fn a_json_error_is_structured_and_has_no_text_prefix() {
441        let error = Error::binder("Referenced column \"nope\" not found\nnext")
442            .with_span(Span::new(7, 11))
443            .into_json();
444        assert_eq!(
445            error.to_string(),
446            "{\"exception_type\":\"Binder\",\"exception_message\":\"Referenced column \\\"nope\\\" not found\\nnext\",\"location\":\"[7,4]\",\"position\":\"7\",\"error_subtype\":\"COLUMN_NOT_FOUND\"}"
447        );
448        assert_eq!(error.code(), ErrorCode::Binder);
449    }
450
451    #[test]
452    fn a_result_is_no_wider_than_the_value_in_it() {
453        // The reason the payload is boxed. If this ever fails, every function in the workspace
454        // got more expensive to return from and nobody noticed.
455        assert_eq!(size_of::<Error>(), size_of::<usize>());
456        assert_eq!(size_of::<Result<String, Error>>(), size_of::<String>());
457    }
458
459    #[test]
460    fn a_span_survives_being_attached() {
461        let error = Error::parser("syntax error at or near \"FROM\"").with_span(Span::new(7, 11));
462        assert_eq!(error.span(), Some(Span::new(7, 11)));
463        assert_eq!(error.span().map(Span::len), Some(4));
464        assert_eq!(error.code(), ErrorCode::Parser);
465    }
466
467    #[test]
468    fn a_fallback_span_keeps_the_more_specific_range() {
469        let specific = Error::binder("missing")
470            .with_span(Span::new(7, 14))
471            .with_fallback_span(Span::new(0, 20));
472        assert_eq!(specific.span(), Some(Span::new(7, 14)));
473        let fallback = Error::binder("missing").with_fallback_span(Span::new(0, 20));
474        assert_eq!(fallback.span(), Some(Span::new(0, 20)));
475        assert_eq!(Error::binder("missing").with_fallback_span(Span::new(0, 0)).span(), None);
476    }
477
478    #[test]
479    fn the_fuzzer_can_tell_our_bugs_from_the_query_s_bugs() {
480        assert!(ErrorCode::Binder.is_user_error());
481        assert!(ErrorCode::Conversion.is_user_error());
482        assert!(!ErrorCode::Internal.is_user_error());
483        assert!(!ErrorCode::OutOfMemory.is_user_error());
484        // Not implemented is ours rather than the query's, because the query was legitimate and we
485        // are the reason it did not run.
486        assert!(!ErrorCode::NotImplemented.is_user_error());
487    }
488}