rusqlite/
error.rs

1use crate::types::FromSqlError;
2use crate::types::Type;
3use crate::{errmsg_to_string, ffi, Result};
4use std::error;
5use std::ffi::{c_char, c_int, NulError};
6use std::fmt;
7use std::path::PathBuf;
8use std::str;
9
10/// Enum listing possible errors from rusqlite.
11#[derive(Debug)]
12#[non_exhaustive]
13pub enum Error {
14    /// An error from an underlying SQLite call.
15    SqliteFailure(ffi::Error, Option<String>),
16
17    /// Error reported when attempting to open a connection when SQLite was
18    /// configured to allow single-threaded use only.
19    SqliteSingleThreadedMode,
20
21    /// Error when the value of a particular column is requested, but it cannot
22    /// be converted to the requested Rust type.
23    FromSqlConversionFailure(usize, Type, Box<dyn error::Error + Send + Sync + 'static>),
24
25    /// Error when SQLite gives us an integral value outside the range of the
26    /// requested type (e.g., trying to get the value 1000 into a `u8`).
27    /// The associated `usize` is the column index,
28    /// and the associated `i64` is the value returned by SQLite.
29    IntegralValueOutOfRange(usize, i64),
30
31    /// Error converting a string to UTF-8.
32    Utf8Error(str::Utf8Error),
33
34    /// Error converting a string to a C-compatible string because it contained
35    /// an embedded nul.
36    NulError(NulError),
37
38    /// Error when using SQL named parameters and passing a parameter name not
39    /// present in the SQL.
40    InvalidParameterName(String),
41
42    /// Error converting a file path to a string.
43    InvalidPath(PathBuf),
44
45    /// Error returned when an [`execute`](crate::Connection::execute) call
46    /// returns rows.
47    ExecuteReturnedResults,
48
49    /// Error when a query that was expected to return at least one row (e.g.,
50    /// for [`query_row`](crate::Connection::query_row)) did not return any.
51    QueryReturnedNoRows,
52
53    /// Error when a query that was expected to return only one row (e.g.,
54    /// for [`query_one`](crate::Connection::query_one)) did return more than one.
55    QueryReturnedMoreThanOneRow,
56
57    /// Error when the value of a particular column is requested, but the index
58    /// is out of range for the statement.
59    InvalidColumnIndex(usize),
60
61    /// Error when the value of a named column is requested, but no column
62    /// matches the name for the statement.
63    InvalidColumnName(String),
64
65    /// Error when the value of a particular column is requested, but the type
66    /// of the result in that column cannot be converted to the requested
67    /// Rust type.
68    InvalidColumnType(usize, String, Type),
69
70    /// Error when a query that was expected to insert one row did not insert
71    /// any or insert many.
72    StatementChangedRows(usize),
73
74    /// Error returned by
75    /// [`functions::Context::get`](crate::functions::Context::get) when the
76    /// function argument cannot be converted to the requested type.
77    #[cfg(feature = "functions")]
78    InvalidFunctionParameterType(usize, Type),
79    /// Error returned by [`vtab::Values::get`](crate::vtab::Values::get) when
80    /// the filter argument cannot be converted to the requested type.
81    #[cfg(feature = "vtab")]
82    InvalidFilterParameterType(usize, Type),
83
84    /// An error case available for implementors of custom user functions (e.g.,
85    /// [`create_scalar_function`](crate::Connection::create_scalar_function)).
86    #[cfg(feature = "functions")]
87    UserFunctionError(Box<dyn error::Error + Send + Sync + 'static>),
88
89    /// Error available for the implementors of the
90    /// [`ToSql`](crate::types::ToSql) trait.
91    ToSqlConversionFailure(Box<dyn error::Error + Send + Sync + 'static>),
92
93    /// Error when the SQL is not a `SELECT`, is not read-only.
94    InvalidQuery,
95
96    /// An error case available for implementors of custom modules (e.g.,
97    /// [`create_module`](crate::Connection::create_module)).
98    #[cfg(feature = "vtab")]
99    ModuleError(String),
100
101    /// An unwinding panic occurs in a UDF (user-defined function).
102    UnwindingPanic,
103
104    /// An error returned when
105    /// [`Context::get_aux`](crate::functions::Context::get_aux) attempts to
106    /// retrieve data of a different type than what had been stored using
107    /// [`Context::set_aux`](crate::functions::Context::set_aux).
108    #[cfg(feature = "functions")]
109    GetAuxWrongType,
110
111    /// Error when the SQL contains multiple statements.
112    MultipleStatement,
113    /// Error when the number of bound parameters does not match the number of
114    /// parameters in the query. The first `usize` is how many parameters were
115    /// given, the 2nd is how many were expected.
116    InvalidParameterCount(usize, usize),
117
118    /// Returned from various functions in the Blob IO positional API. For
119    /// example,
120    /// [`Blob::raw_read_at_exact`](crate::blob::Blob::raw_read_at_exact) will
121    /// return it if the blob has insufficient data.
122    #[cfg(feature = "blob")]
123    BlobSizeError,
124    /// Error referencing a specific token in the input SQL
125    #[cfg(feature = "modern_sqlite")] // 3.38.0
126    SqlInputError {
127        /// error code
128        error: ffi::Error,
129        /// error message
130        msg: String,
131        /// SQL input
132        sql: String,
133        /// byte offset of the start of invalid token
134        offset: c_int,
135    },
136    /// Loadable extension initialization error
137    #[cfg(feature = "loadable_extension")]
138    InitError(ffi::InitError),
139    /// Error when the schema of a particular database is requested, but the index
140    /// is out of range.
141    #[cfg(feature = "modern_sqlite")] // 3.39.0
142    InvalidDatabaseIndex(usize),
143}
144
145impl PartialEq for Error {
146    fn eq(&self, other: &Self) -> bool {
147        match (self, other) {
148            (Self::SqliteFailure(e1, s1), Self::SqliteFailure(e2, s2)) => e1 == e2 && s1 == s2,
149            (Self::SqliteSingleThreadedMode, Self::SqliteSingleThreadedMode) => true,
150            (Self::IntegralValueOutOfRange(i1, n1), Self::IntegralValueOutOfRange(i2, n2)) => {
151                i1 == i2 && n1 == n2
152            }
153            (Self::Utf8Error(e1), Self::Utf8Error(e2)) => e1 == e2,
154            (Self::NulError(e1), Self::NulError(e2)) => e1 == e2,
155            (Self::InvalidParameterName(n1), Self::InvalidParameterName(n2)) => n1 == n2,
156            (Self::InvalidPath(p1), Self::InvalidPath(p2)) => p1 == p2,
157            (Self::ExecuteReturnedResults, Self::ExecuteReturnedResults) => true,
158            (Self::QueryReturnedNoRows, Self::QueryReturnedNoRows) => true,
159            (Self::QueryReturnedMoreThanOneRow, Self::QueryReturnedMoreThanOneRow) => true,
160            (Self::InvalidColumnIndex(i1), Self::InvalidColumnIndex(i2)) => i1 == i2,
161            (Self::InvalidColumnName(n1), Self::InvalidColumnName(n2)) => n1 == n2,
162            (Self::InvalidColumnType(i1, n1, t1), Self::InvalidColumnType(i2, n2, t2)) => {
163                i1 == i2 && t1 == t2 && n1 == n2
164            }
165            (Self::StatementChangedRows(n1), Self::StatementChangedRows(n2)) => n1 == n2,
166            #[cfg(feature = "functions")]
167            (
168                Self::InvalidFunctionParameterType(i1, t1),
169                Self::InvalidFunctionParameterType(i2, t2),
170            ) => i1 == i2 && t1 == t2,
171            #[cfg(feature = "vtab")]
172            (
173                Self::InvalidFilterParameterType(i1, t1),
174                Self::InvalidFilterParameterType(i2, t2),
175            ) => i1 == i2 && t1 == t2,
176            (Self::InvalidQuery, Self::InvalidQuery) => true,
177            #[cfg(feature = "vtab")]
178            (Self::ModuleError(s1), Self::ModuleError(s2)) => s1 == s2,
179            (Self::UnwindingPanic, Self::UnwindingPanic) => true,
180            #[cfg(feature = "functions")]
181            (Self::GetAuxWrongType, Self::GetAuxWrongType) => true,
182            (Self::InvalidParameterCount(i1, n1), Self::InvalidParameterCount(i2, n2)) => {
183                i1 == i2 && n1 == n2
184            }
185            #[cfg(feature = "blob")]
186            (Self::BlobSizeError, Self::BlobSizeError) => true,
187            #[cfg(feature = "modern_sqlite")]
188            (
189                Self::SqlInputError {
190                    error: e1,
191                    msg: m1,
192                    sql: s1,
193                    offset: o1,
194                },
195                Self::SqlInputError {
196                    error: e2,
197                    msg: m2,
198                    sql: s2,
199                    offset: o2,
200                },
201            ) => e1 == e2 && m1 == m2 && s1 == s2 && o1 == o2,
202            #[cfg(feature = "loadable_extension")]
203            (Self::InitError(e1), Self::InitError(e2)) => e1 == e2,
204            #[cfg(feature = "modern_sqlite")]
205            (Self::InvalidDatabaseIndex(i1), Self::InvalidDatabaseIndex(i2)) => i1 == i2,
206            (..) => false,
207        }
208    }
209}
210
211impl From<str::Utf8Error> for Error {
212    #[cold]
213    fn from(err: str::Utf8Error) -> Self {
214        Self::Utf8Error(err)
215    }
216}
217
218impl From<NulError> for Error {
219    #[cold]
220    fn from(err: NulError) -> Self {
221        Self::NulError(err)
222    }
223}
224
225const UNKNOWN_COLUMN: usize = usize::MAX;
226
227/// The conversion isn't precise, but it's convenient to have it
228/// to allow use of `get_raw(…).as_…()?` in callbacks that take `Error`.
229impl From<FromSqlError> for Error {
230    #[cold]
231    fn from(err: FromSqlError) -> Self {
232        // The error type requires index and type fields, but they aren't known in this
233        // context.
234        match err {
235            FromSqlError::OutOfRange(val) => Self::IntegralValueOutOfRange(UNKNOWN_COLUMN, val),
236            FromSqlError::InvalidBlobSize { .. } => {
237                Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Blob, Box::new(err))
238            }
239            FromSqlError::Other(source) => {
240                Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, source)
241            }
242            _ => Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, Box::new(err)),
243        }
244    }
245}
246
247#[cfg(feature = "loadable_extension")]
248impl From<ffi::InitError> for Error {
249    #[cold]
250    fn from(err: ffi::InitError) -> Self {
251        Self::InitError(err)
252    }
253}
254
255impl fmt::Display for Error {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        match *self {
258            Self::SqliteFailure(ref err, None) => err.fmt(f),
259            Self::SqliteFailure(_, Some(ref s)) => write!(f, "{s}"),
260            Self::SqliteSingleThreadedMode => write!(
261                f,
262                "SQLite was compiled or configured for single-threaded use only"
263            ),
264            Self::FromSqlConversionFailure(i, ref t, ref err) => {
265                if i != UNKNOWN_COLUMN {
266                    write!(f, "Conversion error from type {t} at index: {i}, {err}")
267                } else {
268                    err.fmt(f)
269                }
270            }
271            Self::IntegralValueOutOfRange(col, val) => {
272                if col != UNKNOWN_COLUMN {
273                    write!(f, "Integer {val} out of range at index {col}")
274                } else {
275                    write!(f, "Integer {val} out of range")
276                }
277            }
278            Self::Utf8Error(ref err) => err.fmt(f),
279            Self::NulError(ref err) => err.fmt(f),
280            Self::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {name}"),
281            Self::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
282            Self::ExecuteReturnedResults => {
283                write!(f, "Execute returned results - did you mean to call query?")
284            }
285            Self::QueryReturnedNoRows => write!(f, "Query returned no rows"),
286            Self::QueryReturnedMoreThanOneRow => write!(f, "Query returned more than one row"),
287            Self::InvalidColumnIndex(i) => write!(f, "Invalid column index: {i}"),
288            Self::InvalidColumnName(ref name) => write!(f, "Invalid column name: {name}"),
289            Self::InvalidColumnType(i, ref name, ref t) => {
290                write!(f, "Invalid column type {t} at index: {i}, name: {name}")
291            }
292            Self::InvalidParameterCount(i1, n1) => write!(
293                f,
294                "Wrong number of parameters passed to query. Got {i1}, needed {n1}"
295            ),
296            Self::StatementChangedRows(i) => write!(f, "Query changed {i} rows"),
297
298            #[cfg(feature = "functions")]
299            Self::InvalidFunctionParameterType(i, ref t) => {
300                write!(f, "Invalid function parameter type {t} at index {i}")
301            }
302            #[cfg(feature = "vtab")]
303            Self::InvalidFilterParameterType(i, ref t) => {
304                write!(f, "Invalid filter parameter type {t} at index {i}")
305            }
306            #[cfg(feature = "functions")]
307            Self::UserFunctionError(ref err) => err.fmt(f),
308            Self::ToSqlConversionFailure(ref err) => err.fmt(f),
309            Self::InvalidQuery => write!(f, "Query is not read-only"),
310            #[cfg(feature = "vtab")]
311            Self::ModuleError(ref desc) => write!(f, "{desc}"),
312            Self::UnwindingPanic => write!(f, "unwinding panic"),
313            #[cfg(feature = "functions")]
314            Self::GetAuxWrongType => write!(f, "get_aux called with wrong type"),
315            Self::MultipleStatement => write!(f, "Multiple statements provided"),
316            #[cfg(feature = "blob")]
317            Self::BlobSizeError => "Blob size is insufficient".fmt(f),
318            #[cfg(feature = "modern_sqlite")]
319            Self::SqlInputError {
320                ref msg,
321                offset,
322                ref sql,
323                ..
324            } => write!(f, "{msg} in {sql} at offset {offset}"),
325            #[cfg(feature = "loadable_extension")]
326            Self::InitError(ref err) => err.fmt(f),
327            #[cfg(feature = "modern_sqlite")]
328            Self::InvalidDatabaseIndex(i) => write!(f, "Invalid database index: {i}"),
329        }
330    }
331}
332
333impl error::Error for Error {
334    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
335        match *self {
336            Self::SqliteFailure(ref err, _) => Some(err),
337            Self::Utf8Error(ref err) => Some(err),
338            Self::NulError(ref err) => Some(err),
339
340            Self::IntegralValueOutOfRange(..)
341            | Self::SqliteSingleThreadedMode
342            | Self::InvalidParameterName(_)
343            | Self::ExecuteReturnedResults
344            | Self::QueryReturnedNoRows
345            | Self::QueryReturnedMoreThanOneRow
346            | Self::InvalidColumnIndex(_)
347            | Self::InvalidColumnName(_)
348            | Self::InvalidColumnType(..)
349            | Self::InvalidPath(_)
350            | Self::InvalidParameterCount(..)
351            | Self::StatementChangedRows(_)
352            | Self::InvalidQuery
353            | Self::MultipleStatement => None,
354
355            #[cfg(feature = "functions")]
356            Self::InvalidFunctionParameterType(..) => None,
357            #[cfg(feature = "vtab")]
358            Self::InvalidFilterParameterType(..) => None,
359
360            #[cfg(feature = "functions")]
361            Self::UserFunctionError(ref err) => Some(&**err),
362
363            Self::FromSqlConversionFailure(_, _, ref err)
364            | Self::ToSqlConversionFailure(ref err) => Some(&**err),
365
366            #[cfg(feature = "vtab")]
367            Self::ModuleError(_) => None,
368
369            Self::UnwindingPanic => None,
370
371            #[cfg(feature = "functions")]
372            Self::GetAuxWrongType => None,
373
374            #[cfg(feature = "blob")]
375            Self::BlobSizeError => None,
376            #[cfg(feature = "modern_sqlite")]
377            Self::SqlInputError { ref error, .. } => Some(error),
378            #[cfg(feature = "loadable_extension")]
379            Self::InitError(ref err) => Some(err),
380            #[cfg(feature = "modern_sqlite")]
381            Self::InvalidDatabaseIndex(_) => None,
382        }
383    }
384}
385
386impl Error {
387    /// Returns the underlying SQLite error if this is [`Error::SqliteFailure`].
388    #[inline]
389    #[must_use]
390    pub fn sqlite_error(&self) -> Option<&ffi::Error> {
391        match self {
392            Self::SqliteFailure(error, _) => Some(error),
393            _ => None,
394        }
395    }
396
397    /// Returns the underlying SQLite error code if this is
398    /// [`Error::SqliteFailure`].
399    #[inline]
400    #[must_use]
401    pub fn sqlite_error_code(&self) -> Option<ffi::ErrorCode> {
402        self.sqlite_error().map(|error| error.code)
403    }
404}
405
406// These are public but not re-exported by lib.rs, so only visible within crate.
407
408#[cold]
409pub fn error_from_sqlite_code(code: c_int, message: Option<String>) -> Error {
410    Error::SqliteFailure(ffi::Error::new(code), message)
411}
412
413macro_rules! err {
414    ($code:expr $(,)?) => {
415        $crate::error::error_from_sqlite_code($code, None)
416    };
417    ($code:expr, $msg:literal $(,)?) => {
418        $crate::error::error_from_sqlite_code($code, Some(format!($msg)))
419    };
420    ($code:expr, $err:expr $(,)?) => {
421        $crate::error::error_from_sqlite_code($code, Some(format!($err)))
422    };
423    ($code:expr, $fmt:expr, $($arg:tt)*) => {
424        $crate::error::error_from_sqlite_code($code, Some(format!($fmt, $($arg)*)))
425    };
426}
427
428#[cold]
429pub unsafe fn error_from_handle(db: *mut ffi::sqlite3, code: c_int) -> Error {
430    error_from_sqlite_code(code, error_msg(db, code))
431}
432
433unsafe fn error_msg(db: *mut ffi::sqlite3, code: c_int) -> Option<String> {
434    if db.is_null() || ffi::sqlite3_errcode(db) != code {
435        let err_str = ffi::sqlite3_errstr(code);
436        if err_str.is_null() {
437            None
438        } else {
439            Some(errmsg_to_string(err_str))
440        }
441    } else {
442        Some(errmsg_to_string(ffi::sqlite3_errmsg(db)))
443    }
444}
445
446pub unsafe fn decode_result_raw(db: *mut ffi::sqlite3, code: c_int) -> Result<()> {
447    if code == ffi::SQLITE_OK {
448        Ok(())
449    } else {
450        Err(error_from_handle(db, code))
451    }
452}
453
454#[cold]
455#[cfg(not(feature = "modern_sqlite"))] // SQLite >= 3.38.0
456pub unsafe fn error_with_offset(db: *mut ffi::sqlite3, code: c_int, _sql: &str) -> Error {
457    error_from_handle(db, code)
458}
459
460#[cold]
461#[cfg(feature = "modern_sqlite")] // SQLite >= 3.38.0
462pub unsafe fn error_with_offset(db: *mut ffi::sqlite3, code: c_int, sql: &str) -> Error {
463    if db.is_null() {
464        error_from_sqlite_code(code, None)
465    } else {
466        let error = ffi::Error::new(code);
467        let msg = error_msg(db, code);
468        if ffi::ErrorCode::Unknown == error.code {
469            let offset = ffi::sqlite3_error_offset(db);
470            if offset >= 0 {
471                return Error::SqlInputError {
472                    error,
473                    msg: msg.unwrap_or("error".to_owned()),
474                    sql: sql.to_owned(),
475                    offset,
476                };
477            }
478        }
479        Error::SqliteFailure(error, msg)
480    }
481}
482
483pub fn check(code: c_int) -> Result<()> {
484    if code != ffi::SQLITE_OK {
485        Err(error_from_sqlite_code(code, None))
486    } else {
487        Ok(())
488    }
489}
490
491/// Transform Rust error to SQLite error (message and code).
492/// # Safety
493/// This function is unsafe because it uses raw pointer
494pub unsafe fn to_sqlite_error(e: &Error, err_msg: *mut *mut c_char) -> c_int {
495    use crate::util::alloc;
496    match e {
497        Error::SqliteFailure(err, s) => {
498            if let Some(s) = s {
499                *err_msg = alloc(s);
500            }
501            err.extended_code
502        }
503        err => {
504            *err_msg = alloc(&err.to_string());
505            ffi::SQLITE_ERROR
506        }
507    }
508}