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