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 it does not mean anything, for example a column that is not in scope.
60    Binder,
61    /// A named object is missing, or one that should be missing is not.
62    Catalog,
63    /// A value will not convert to the type it is being asked for.
64    Conversion,
65    /// A value is outside what its type can hold.
66    OutOfRange,
67    /// An argument is wrong in a way that is not a type error, for example a negative length.
68    InvalidInput,
69    /// An allocation failed or a memory limit was reached. An error, never an abort.
70    OutOfMemory,
71    /// The filesystem, the network or the object store said no.
72    Io,
73    /// It is in the plan and it is not built yet.
74    NotImplemented,
75    /// A primary key, unique, not null or check constraint was violated.
76    Constraint,
77    /// A conflict, an abort, or a statement issued outside a transaction that needs one.
78    Transaction,
79    /// The query was cancelled. Cooperative, checked at morsel boundaries.
80    Interrupt,
81    /// An invariant this code is responsible for does not hold. Always a bug here, never in the
82    /// query.
83    Internal,
84}
85
86impl ErrorCode {
87    /// The prefix DuckDB puts on a message with this code.
88    ///
89    /// Compatibility obligation from `spec/12-duckdb-compat.md` section 12.5: a great many tests
90    /// in the wild assert on the exact text of an error, so the prefix is DuckDB's spelling
91    /// including the parts that look like typos. `Not implemented Error` really is capitalised
92    /// that way upstream, and `INTERNAL Error` really is shouted.
93    #[must_use]
94    pub const fn duckdb_name(self) -> &'static str {
95        match self {
96            Self::Parser => "Parser Error",
97            Self::Binder => "Binder Error",
98            Self::Catalog => "Catalog Error",
99            Self::Conversion => "Conversion Error",
100            Self::OutOfRange => "Out of Range Error",
101            Self::InvalidInput => "Invalid Input Error",
102            Self::OutOfMemory => "Out of Memory Error",
103            Self::Io => "IO Error",
104            Self::NotImplemented => "Not implemented Error",
105            Self::Constraint => "Constraint Error",
106            Self::Transaction => "TransactionContext Error",
107            Self::Interrupt => "Interrupt Error",
108            Self::Internal => "INTERNAL Error",
109        }
110    }
111
112    /// Whether an error with this code says something about the query rather than about us.
113    ///
114    /// Used by the fuzzing harness in `spec/16-testing.md` section 16.4, which treats a rejected
115    /// query as a normal outcome and an internal error as a finding.
116    #[must_use]
117    pub const fn is_user_error(self) -> bool {
118        matches!(
119            self,
120            Self::Parser
121                | Self::Binder
122                | Self::Catalog
123                | Self::Conversion
124                | Self::OutOfRange
125                | Self::InvalidInput
126                | Self::Constraint
127                | Self::Transaction
128        )
129    }
130}
131
132impl fmt::Display for ErrorCode {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.write_str(self.duckdb_name())
135    }
136}
137
138/// An error, carrying a code, a message and optionally where in the query it happened.
139///
140/// The payload is boxed so that `Error` is one pointer wide, which keeps `Result<T>` the same size
141/// as `T` for every `T` that has a niche. Errors are rare and results are returned from every
142/// function in the workspace, so the cost belongs on the rare path.
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct Error(Box<Payload>);
145
146#[derive(Debug, Clone, PartialEq, Eq)]
147struct Payload {
148    code: ErrorCode,
149    message: String,
150    span: Option<Span>,
151}
152
153impl Error {
154    /// An error with a code and a message and no span.
155    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
156        Self(Box::new(Payload { code, message: message.into(), span: None }))
157    }
158
159    /// The same error, with the part of the query it is about.
160    #[must_use]
161    pub fn with_span(mut self, span: Span) -> Self {
162        self.0.span = Some(span);
163        self
164    }
165
166    /// What kind of thing went wrong.
167    #[must_use]
168    pub fn code(&self) -> ErrorCode {
169        self.0.code
170    }
171
172    /// The message, without the code prefix that `Display` adds.
173    #[must_use]
174    pub fn message(&self) -> &str {
175        &self.0.message
176    }
177
178    /// Where in the query text this is about, if it is about a place.
179    #[must_use]
180    pub fn span(&self) -> Option<Span> {
181        self.0.span
182    }
183
184    /// The text is not SQL.
185    pub fn parser(message: impl Into<String>) -> Self {
186        Self::new(ErrorCode::Parser, message)
187    }
188
189    /// The text is SQL and it does not mean anything.
190    pub fn binder(message: impl Into<String>) -> Self {
191        Self::new(ErrorCode::Binder, message)
192    }
193
194    /// A named object is missing, or one that should be missing is not.
195    pub fn catalog(message: impl Into<String>) -> Self {
196        Self::new(ErrorCode::Catalog, message)
197    }
198
199    /// A value will not convert to the type it is being asked for.
200    pub fn conversion(message: impl Into<String>) -> Self {
201        Self::new(ErrorCode::Conversion, message)
202    }
203
204    /// A value is outside what its type can hold.
205    pub fn out_of_range(message: impl Into<String>) -> Self {
206        Self::new(ErrorCode::OutOfRange, message)
207    }
208
209    /// An argument is wrong in a way that is not a type error.
210    pub fn invalid_input(message: impl Into<String>) -> Self {
211        Self::new(ErrorCode::InvalidInput, message)
212    }
213
214    /// An allocation failed or a memory limit was reached.
215    pub fn out_of_memory(message: impl Into<String>) -> Self {
216        Self::new(ErrorCode::OutOfMemory, message)
217    }
218
219    /// The filesystem, the network or the object store said no.
220    pub fn io(message: impl Into<String>) -> Self {
221        Self::new(ErrorCode::Io, message)
222    }
223
224    /// It is in the plan and it is not built yet.
225    pub fn not_implemented(message: impl Into<String>) -> Self {
226        Self::new(ErrorCode::NotImplemented, message)
227    }
228
229    /// A constraint was violated.
230    pub fn constraint(message: impl Into<String>) -> Self {
231        Self::new(ErrorCode::Constraint, message)
232    }
233
234    /// A conflict, an abort, or a statement issued outside a transaction that needs one.
235    pub fn transaction(message: impl Into<String>) -> Self {
236        Self::new(ErrorCode::Transaction, message)
237    }
238
239    /// The query was cancelled.
240    pub fn interrupt(message: impl Into<String>) -> Self {
241        Self::new(ErrorCode::Interrupt, message)
242    }
243
244    /// An invariant this code is responsible for does not hold.
245    ///
246    /// Reaching this is always a bug in the database and never a bug in the query, which is why it
247    /// reads differently from the others and why the fuzzer treats it as a finding.
248    pub fn internal(message: impl Into<String>) -> Self {
249        Self::new(ErrorCode::Internal, message)
250    }
251}
252
253impl fmt::Display for Error {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        write!(f, "{}: {}", self.0.code, self.0.message)
256    }
257}
258
259impl std::error::Error for Error {}
260
261impl From<std::io::Error> for Error {
262    fn from(error: std::io::Error) -> Self {
263        Self::io(error.to_string())
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::{Error, ErrorCode, Span};
270
271    #[test]
272    fn an_error_prints_the_way_duckdb_prints_it() {
273        let error = Error::binder("Referenced column \"nope\" not found in FROM clause!");
274        assert_eq!(
275            error.to_string(),
276            "Binder Error: Referenced column \"nope\" not found in FROM clause!"
277        );
278    }
279
280    #[test]
281    fn a_result_is_no_wider_than_the_value_in_it() {
282        // The reason the payload is boxed. If this ever fails, every function in the workspace
283        // got more expensive to return from and nobody noticed.
284        assert_eq!(size_of::<Error>(), size_of::<usize>());
285        assert_eq!(size_of::<Result<String, Error>>(), size_of::<String>());
286    }
287
288    #[test]
289    fn a_span_survives_being_attached() {
290        let error = Error::parser("syntax error at or near \"FROM\"").with_span(Span::new(7, 11));
291        assert_eq!(error.span(), Some(Span::new(7, 11)));
292        assert_eq!(error.span().map(Span::len), Some(4));
293        assert_eq!(error.code(), ErrorCode::Parser);
294    }
295
296    #[test]
297    fn the_fuzzer_can_tell_our_bugs_from_the_query_s_bugs() {
298        assert!(ErrorCode::Binder.is_user_error());
299        assert!(ErrorCode::Conversion.is_user_error());
300        assert!(!ErrorCode::Internal.is_user_error());
301        assert!(!ErrorCode::OutOfMemory.is_user_error());
302        // Not implemented is ours rather than the query's, because the query was legitimate and we
303        // are the reason it did not run.
304        assert!(!ErrorCode::NotImplemented.is_user_error());
305    }
306}