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    /// What kind of thing went wrong.
180    #[must_use]
181    pub fn code(&self) -> ErrorCode {
182        self.0.code
183    }
184
185    /// The message, without the code prefix that `Display` adds.
186    #[must_use]
187    pub fn message(&self) -> &str {
188        &self.0.message
189    }
190
191    /// Where in the query text this is about, if it is about a place.
192    #[must_use]
193    pub fn span(&self) -> Option<Span> {
194        self.0.span
195    }
196
197    /// Renders this error as the structured JSON form DuckDB returns for `errors_as_json`.
198    #[must_use]
199    pub fn into_json(mut self) -> Self {
200        let exception_type = self.0.code.json_name();
201        let subtype = self.0.code.json_subtype(&self.0.message);
202        let mut fields = vec![
203            ("exception_type", exception_type.to_string()),
204            ("exception_message", self.0.message.clone()),
205        ];
206        if let Some(span) = self.0.span {
207            fields.push(("location", format!("[{},{}]", span.start, span.len())));
208            fields.push(("position", span.start.to_string()));
209        }
210        if let Some(subtype) = subtype {
211            fields.push(("error_subtype", subtype.to_string()));
212        }
213        self.0.message = json_object(&fields);
214        self.0.message_only = true;
215        self
216    }
217
218    /// The text is not SQL.
219    pub fn parser(message: impl Into<String>) -> Self {
220        Self::new(ErrorCode::Parser, message)
221    }
222
223    /// The text is SQL and a value in it is not one the statement can take.
224    pub fn syntax(message: impl Into<String>) -> Self {
225        Self::new(ErrorCode::Syntax, message)
226    }
227
228    /// The text is SQL and it does not mean anything.
229    pub fn binder(message: impl Into<String>) -> Self {
230        Self::new(ErrorCode::Binder, message)
231    }
232
233    /// A named object is missing, or one that should be missing is not.
234    pub fn catalog(message: impl Into<String>) -> Self {
235        Self::new(ErrorCode::Catalog, message)
236    }
237
238    /// A value will not convert to the type it is being asked for.
239    pub fn conversion(message: impl Into<String>) -> Self {
240        Self::new(ErrorCode::Conversion, message)
241    }
242
243    /// A value is outside what its type can hold.
244    pub fn out_of_range(message: impl Into<String>) -> Self {
245        Self::new(ErrorCode::OutOfRange, message)
246    }
247
248    /// An argument is wrong in a way that is not a type error.
249    pub fn invalid_input(message: impl Into<String>) -> Self {
250        Self::new(ErrorCode::InvalidInput, message)
251    }
252
253    /// An allocation failed or a memory limit was reached.
254    pub fn out_of_memory(message: impl Into<String>) -> Self {
255        Self::new(ErrorCode::OutOfMemory, message)
256    }
257
258    /// The filesystem, the network or the object store said no.
259    pub fn io(message: impl Into<String>) -> Self {
260        Self::new(ErrorCode::Io, message)
261    }
262
263    /// It is in the plan and it is not built yet.
264    pub fn not_implemented(message: impl Into<String>) -> Self {
265        Self::new(ErrorCode::NotImplemented, message)
266    }
267
268    /// A constraint was violated.
269    pub fn constraint(message: impl Into<String>) -> Self {
270        Self::new(ErrorCode::Constraint, message)
271    }
272
273    /// A conflict, an abort, or a statement issued outside a transaction that needs one.
274    pub fn transaction(message: impl Into<String>) -> Self {
275        Self::new(ErrorCode::Transaction, message)
276    }
277
278    /// A setting cannot be applied in the current engine configuration.
279    pub fn settings(message: impl Into<String>) -> Self {
280        Self::new(ErrorCode::Settings, message)
281    }
282
283    /// The query was cancelled.
284    pub fn interrupt(message: impl Into<String>) -> Self {
285        Self::new(ErrorCode::Interrupt, message)
286    }
287
288    /// An invariant this code is responsible for does not hold.
289    ///
290    /// Reaching this is always a bug in the database and never a bug in the query, which is why it
291    /// reads differently from the others and why the fuzzer treats it as a finding.
292    pub fn internal(message: impl Into<String>) -> Self {
293        Self::new(ErrorCode::Internal, message)
294    }
295}
296
297impl fmt::Display for Error {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        if self.0.message_only {
300            return f.write_str(&self.0.message);
301        }
302        write!(f, "{}: {}", self.0.code, self.0.message)
303    }
304}
305
306impl ErrorCode {
307    const fn json_name(self) -> &'static str {
308        match self {
309            Self::Parser => "Parser",
310            Self::Syntax => "Syntax",
311            Self::Binder => "Binder",
312            Self::Catalog => "Catalog",
313            Self::Conversion => "Conversion",
314            Self::OutOfRange => "Out of Range",
315            Self::InvalidInput => "Invalid Input",
316            Self::OutOfMemory => "Out of Memory",
317            Self::Io => "IO",
318            Self::NotImplemented => "Not implemented",
319            Self::Constraint => "Constraint",
320            Self::Transaction => "TransactionContext",
321            Self::Settings => "Settings",
322            Self::Interrupt => "Interrupt",
323            Self::Internal => "INTERNAL",
324        }
325    }
326
327    fn json_subtype(self, message: &str) -> Option<&'static str> {
328        match self {
329            Self::Parser => Some("SYNTAX_ERROR"),
330            Self::Binder if message.starts_with("Referenced column") => Some("COLUMN_NOT_FOUND"),
331            Self::Binder if message.contains("No function matches") => Some("NO_MATCHING_FUNCTION"),
332            Self::Catalog if message.contains("does not exist") => Some("MISSING_ENTRY"),
333            _ => None,
334        }
335    }
336}
337
338fn json_object(fields: &[(&str, String)]) -> String {
339    let mut out = String::from("{");
340    for (index, (name, value)) in fields.iter().enumerate() {
341        if index != 0 {
342            out.push(',');
343        }
344        out.push('"');
345        out.push_str(name);
346        out.push_str("\":\"");
347        for character in value.chars() {
348            match character {
349                '"' => out.push_str("\\\""),
350                '\\' => out.push_str("\\\\"),
351                '\n' => out.push_str("\\n"),
352                '\r' => out.push_str("\\r"),
353                '\t' => out.push_str("\\t"),
354                character if character <= '\u{1f}' => {
355                    use std::fmt::Write as _;
356                    let _ = write!(out, "\\u{:04x}", character as u32);
357                }
358                character => out.push(character),
359            }
360        }
361        out.push('"');
362    }
363    out.push('}');
364    out
365}
366
367impl std::error::Error for Error {}
368
369impl From<std::io::Error> for Error {
370    fn from(error: std::io::Error) -> Self {
371        Self::io(error.to_string())
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::{Error, ErrorCode, Span};
378
379    #[test]
380    fn an_error_prints_the_way_duckdb_prints_it() {
381        let error = Error::binder("Referenced column \"nope\" not found in FROM clause!");
382        assert_eq!(
383            error.to_string(),
384            "Binder Error: Referenced column \"nope\" not found in FROM clause!"
385        );
386    }
387
388    #[test]
389    fn a_json_error_is_structured_and_has_no_text_prefix() {
390        let error = Error::binder("Referenced column \"nope\" not found\nnext")
391            .with_span(Span::new(7, 11))
392            .into_json();
393        assert_eq!(
394            error.to_string(),
395            "{\"exception_type\":\"Binder\",\"exception_message\":\"Referenced column \\\"nope\\\" not found\\nnext\",\"location\":\"[7,4]\",\"position\":\"7\",\"error_subtype\":\"COLUMN_NOT_FOUND\"}"
396        );
397        assert_eq!(error.code(), ErrorCode::Binder);
398    }
399
400    #[test]
401    fn a_result_is_no_wider_than_the_value_in_it() {
402        // The reason the payload is boxed. If this ever fails, every function in the workspace
403        // got more expensive to return from and nobody noticed.
404        assert_eq!(size_of::<Error>(), size_of::<usize>());
405        assert_eq!(size_of::<Result<String, Error>>(), size_of::<String>());
406    }
407
408    #[test]
409    fn a_span_survives_being_attached() {
410        let error = Error::parser("syntax error at or near \"FROM\"").with_span(Span::new(7, 11));
411        assert_eq!(error.span(), Some(Span::new(7, 11)));
412        assert_eq!(error.span().map(Span::len), Some(4));
413        assert_eq!(error.code(), ErrorCode::Parser);
414    }
415
416    #[test]
417    fn the_fuzzer_can_tell_our_bugs_from_the_query_s_bugs() {
418        assert!(ErrorCode::Binder.is_user_error());
419        assert!(ErrorCode::Conversion.is_user_error());
420        assert!(!ErrorCode::Internal.is_user_error());
421        assert!(!ErrorCode::OutOfMemory.is_user_error());
422        // Not implemented is ours rather than the query's, because the query was legitimate and we
423        // are the reason it did not run.
424        assert!(!ErrorCode::NotImplemented.is_user_error());
425    }
426}