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